-
Notifications
You must be signed in to change notification settings - Fork 129
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add binder for annotated custom Principal
#1522
Changes from all commits
a1bef87
3d2057c
a915120
909a127
b4a3f4e
570ca16
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
/* | ||
* Copyright 2017-2023 original authors | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
package io.micronaut.security.annotation; | ||
|
||
import io.micronaut.core.bind.annotation.Bindable; | ||
|
||
import java.lang.annotation.Documented; | ||
import java.lang.annotation.ElementType; | ||
import java.lang.annotation.Inherited; | ||
import java.lang.annotation.Retention; | ||
import java.lang.annotation.RetentionPolicy; | ||
import java.lang.annotation.Target; | ||
|
||
/** | ||
* An annotation that can be applied to a method argument to indicate that it is bound from the user | ||
* object for the currently active authentication. | ||
* | ||
* @author Jeremy Grelle | ||
* @since 4.5.0 | ||
*/ | ||
@Target({ElementType.PARAMETER}) | ||
@Retention(RetentionPolicy.RUNTIME) | ||
@Bindable | ||
@Inherited | ||
@Documented | ||
public @interface User { | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
/* | ||
* Copyright 2017-2023 original authors | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
package io.micronaut.security.authentication; | ||
|
||
import io.micronaut.core.convert.ArgumentConversionContext; | ||
import io.micronaut.http.HttpRequest; | ||
import io.micronaut.http.bind.binders.AnnotatedRequestArgumentBinder; | ||
import io.micronaut.security.annotation.User; | ||
import io.micronaut.security.filters.SecurityFilter; | ||
import jakarta.inject.Singleton; | ||
|
||
import java.security.Principal; | ||
import java.util.Optional; | ||
|
||
/** | ||
* Binds the authentication object to a route argument annotated with {@link User}. | ||
* | ||
* @param <T> The bound subtype of {@link Principal} | ||
* @author Jeremy Grelle | ||
* @since 4.5.0 | ||
*/ | ||
@Singleton | ||
public class UserArgumentBinder<T extends Principal> implements AnnotatedRequestArgumentBinder<User, T> { | ||
|
||
@Override | ||
public Class<User> getAnnotationType() { | ||
return User.class; | ||
} | ||
|
||
@Override | ||
public BindingResult<T> bind(ArgumentConversionContext<T> context, HttpRequest<?> source) { | ||
if (!source.getAttributes().contains(SecurityFilter.KEY)) { | ||
return BindingResult.unsatisfied(); | ||
} | ||
|
||
final Optional<T> existing = source.getUserPrincipal(context.getArgument().getType()); | ||
return existing.isPresent() ? (() -> existing) : BindingResult.empty(); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -19,15 +19,23 @@ | |
import io.micronaut.security.MockAuthenticationProvider | ||
import io.micronaut.security.SuccessAuthenticationScenario | ||
import io.micronaut.security.annotation.Secured | ||
import io.micronaut.security.annotation.User | ||
import io.micronaut.security.authentication.Authentication | ||
import io.micronaut.security.authentication.AuthenticationArgumentBinder | ||
import io.micronaut.security.authentication.AuthenticationFailureReason | ||
import io.micronaut.security.authentication.AuthenticationRequest | ||
import io.micronaut.security.authentication.AuthenticationResponse | ||
import io.micronaut.security.authentication.ClientAuthentication | ||
import io.micronaut.security.authentication.PrincipalArgumentBinder | ||
import io.micronaut.security.authentication.ServerAuthentication | ||
import io.micronaut.security.authentication.UserArgumentBinder | ||
import io.micronaut.security.rules.SecurityRule | ||
import io.micronaut.security.rules.SecurityRuleResult | ||
import io.micronaut.security.rules.SensitiveEndpointRule | ||
import io.micronaut.security.testutils.EmbeddedServerSpecification | ||
import jakarta.inject.Singleton | ||
import org.reactivestreams.Publisher | ||
import reactor.core.publisher.Flux | ||
import reactor.core.publisher.Mono | ||
|
||
import java.security.Principal | ||
|
@@ -95,7 +103,7 @@ | |
|
||
void "Authentication Argument Binders binds Authentication if return type is Single"() { | ||
expect: | ||
embeddedServer.applicationContext.getBean(PrincipalArgumentBinder.class) | ||
embeddedServer.applicationContext.getBean(AuthenticationArgumentBinder.class) | ||
|
||
when: | ||
HttpResponse<String> response = client.exchange(HttpRequest.GET("/argumentbinder/singleauthentication") | ||
|
@@ -105,6 +113,56 @@ | |
response.body() == 'You are valid' | ||
} | ||
|
||
void "Authentication Argument Binders binds annotated subtype of Principal"() { | ||
expect: | ||
embeddedServer.applicationContext.containsBean(UserArgumentBinder.class) | ||
|
||
when: | ||
HttpResponse<String> response = client.exchange(HttpRequest.GET("/subtypeargumentbinder/single-server-authentication") | ||
.basicAuth("valid", "password"), String) | ||
|
||
then: | ||
response.body() == 'You are valid' | ||
} | ||
|
||
void "Authentication Argument Binders cannot bind annotated subtype of Principal if subtype doesn't match request.getPrincipal"() { | ||
expect: | ||
embeddedServer.applicationContext.containsBean(UserArgumentBinder.class) | ||
|
||
when: | ||
client.exchange(HttpRequest.GET("/subtypeargumentbinder/single-client-authentication") | ||
.basicAuth("valid", "password"), String) | ||
|
||
then: | ||
HttpClientResponseException e = thrown() | ||
e.status == HttpStatus.BAD_REQUEST | ||
} | ||
|
||
void "Authentication Argument Binders cannot bind non-annotated subtype of Principal"() { | ||
expect: | ||
embeddedServer.applicationContext.containsBean(UserArgumentBinder.class) | ||
|
||
when: | ||
client.exchange(HttpRequest.GET("/subtypeargumentbinder/single-no-user-authentication") | ||
.basicAuth("valid", "password"), String) | ||
|
||
then: | ||
HttpClientResponseException e = thrown(HttpClientResponseException) | ||
e.status == HttpStatus.BAD_REQUEST | ||
} | ||
|
||
void "Authentication Argument Binders binds annotated custom subtype of Principal"() { | ||
expect: | ||
embeddedServer.applicationContext.contains(UserArgumentBinder.class) | ||
Check failure on line 156 in security/src/test/groovy/io/micronaut/security/authorization/AuthorizationSpec.groovy
|
||
|
||
when: | ||
HttpResponse<String> response = client.exchange(HttpRequest.GET("/customuserargumentbinder/single-user") | ||
.basicAuth("custom", "password"), String) | ||
|
||
then: | ||
response.body() == 'You are custom' | ||
} | ||
|
||
void "test accessing the url map controller without authentication"() { | ||
when: | ||
client.exchange(HttpRequest.GET("/urlMap/authenticated")) | ||
|
@@ -318,6 +376,42 @@ | |
} | ||
} | ||
|
||
@Requires(property = 'spec.name', value = 'AuthorizationSpec') | ||
@Controller('/subtypeargumentbinder') | ||
@Secured("isAuthenticated()") | ||
static class PrincipalSubtypeArgumentBinderController { | ||
|
||
@Get("/single-server-authentication") | ||
@SingleResult | ||
Publisher<String> singleServerAuthentication(@User ServerAuthentication authentication) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. all of these methods return There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I agree. I wasn't sure if the original spec author was explicitly trying to make sure it worked with |
||
Mono.just("You are ${authentication.getName()}".toString()) | ||
} | ||
|
||
@Get("/single-client-authentication") | ||
@SingleResult | ||
Publisher<String> singleClientAuthentication(@User ClientAuthentication authentication) { | ||
Mono.just("You are ${authentication.getName()}".toString()) | ||
} | ||
|
||
@Get("/single-no-user-authentication") | ||
@SingleResult | ||
Publisher<String> singleNoUserAuthentication(ServerAuthentication authentication) { | ||
Mono.just("You are ${authentication.getName()}".toString()) | ||
} | ||
} | ||
|
||
@Requires(property = 'spec.name', value = 'AuthorizationSpec') | ||
@Controller('/customuserargumentbinder') | ||
@Secured("isAuthenticated()") | ||
static class CustomUserArgumentBinderController { | ||
|
||
@Get("/single-user") | ||
@SingleResult | ||
Publisher<String> singleServerAuthentication(@User TestingAuthenticationProvider.CustomAuthentication authentication) { | ||
Mono.just("You are ${authentication.getName()}".toString()) | ||
} | ||
} | ||
|
||
@Requires(property = 'spec.name', value = 'AuthorizationSpec') | ||
@Controller("/urlMap") | ||
static class UrlMapController { | ||
|
@@ -344,6 +438,7 @@ | |
TestingAuthenticationProvider() { | ||
super([ | ||
new SuccessAuthenticationScenario("valid","password"), | ||
new SuccessAuthenticationScenario("custom", "password"), | ||
new SuccessAuthenticationScenario("admin",["ROLE_ADMIN"]) | ||
], [ | ||
new FailedAuthenticationScenario("disabled", AuthenticationFailureReason.USER_DISABLED), | ||
|
@@ -353,6 +448,36 @@ | |
new FailedAuthenticationScenario("invalidPassword", AuthenticationFailureReason.CREDENTIALS_DO_NOT_MATCH), | ||
]) | ||
} | ||
|
||
@Override | ||
Publisher<AuthenticationResponse> authenticate(Object httpRequest, AuthenticationRequest authenticationRequest) { | ||
return Flux.from(super.authenticate(httpRequest, authenticationRequest)).map(response -> { | ||
if (response.authenticated && response.getAuthentication().orElseThrow().name == 'custom') { | ||
return new CustomAuthenticationResponse('custom') | ||
} | ||
return response | ||
}) | ||
} | ||
|
||
static class CustomAuthenticationResponse implements AuthenticationResponse { | ||
|
||
private final String username | ||
|
||
CustomAuthenticationResponse(String username) { | ||
this.username = username | ||
} | ||
|
||
@Override | ||
Optional<Authentication> getAuthentication() { | ||
return Optional.of(new CustomAuthentication(this.username, Collections.emptyList(), Collections.emptyMap())) | ||
} | ||
} | ||
|
||
static class CustomAuthentication extends ServerAuthentication { | ||
CustomAuthentication(String name, Collection<String> roles, Map<String, Object> attributes) { | ||
super(name, roles, attributes) | ||
} | ||
} | ||
} | ||
|
||
@Requires(property = 'spec.name', value = 'AuthorizationSpec') | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why this change?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It seemed more appropriate since that is the binder that gets used when the method argument is
Authentication
.