This is my application property file:
spring.security.oauth2.client.registration.myclient.client-id=SampleClientId
spring.security.oauth2.client.registration.myclient.client-secret=secret
spring.security.oauth2.client.provider.myclient.authorization-uri=http://localhost:8081/auth/oauth/authorize
spring.security.oauth2.client.provider.myclient.token-uri=http://localhost:8081/auth/oauth/token
spring.security.oauth2.client.provider.myclient.user-info-uri=http://localhost:8081/auth/user/me
spring.security.oauth2.client.registration.myclient.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.myclient.redirect-uri=http://localhost:8080/hellouser
spring.security.oauth2.client.provider.myclient.userNameAttribute=user
This is my configuration class:
#Configuration class SecurityConfig extends WebSecurityConfigurerAdapter {
#throws[Exception]
override protected def configure(http: HttpSecurity): Unit = {
http.authorizeRequests.anyRequest.authenticated.and.oauth2Login
.redirectionEndpoint()
.baseUri("/")
}
}
and this my controller:
case class Message(val string: String)
#Controller
class SuccessController {
#GetMapping(path = Array("/hellouser"), produces = Array(MediaType.APPLICATION_JSON_VALUE))
def getHelloUser(model: Model, authentication: OAuth2AuthenticationToken ): Message = {
Message("hello user")
}
}
When I do login, I get back ERR_TOO_MANY_REDIRECTS
In network section of developer console I see these three call are infinitely repeated:
http://localhost:8081/auth/oauth/authorize?response_type=code&client_id=SampleClientId&state=xyz&redirect_uri=http://localhost:8080/hellouser
http://localhost:8080/hellouser?code=abc&state=xyz
http://localhost:8080/oauth2/authorization/myclient
What I am doing wrong?
Thank you
Do not set your re-direct URI to an API.
The redirect URI in the authorization code flow is used to pick up the authorization code so it then can be exchanged for tokens.
What is happening in your setup is
Request Starts
User is not logged in
Redirect to Authorization login
Redirect back from IdP to predetermined URI
Request to API /helloworld
Go to step 2.
https://auth0.com/docs/flows/concepts/auth-code has a visual of this, you are not making it to step 4, but short circuiting the flow back to step 1
Your config makes it that the auth code flow never completes. You should just keep the Spring default redirect URI and remove spring.security.oauth2.client.registration.myclient.redirect-uri=http://localhost:8080/hellouser
Nor should you need to set the redirectionEndpoint#baseUri config.
Edit,
Aditional clarification is that with Spring Security the initial request at step 1 is saved, and when the Authorization Code Flow completes at step 4 Spring will automatically replay the saved request.
Related
I am new to Spring Boot Security. I am performing validation of licenseKey in every end-point in REST call. It is working fine.
I want to do it in a common way like SecurityConfig extends WebSecurityConfigurerAdapter {} class so that I should not pass extra parameter in methods for validation. It means there should be common validation if the licenseKey exists then the REST calls should be authorized to go otherwise, it should throw error. Currently I am passing HttpServletRequest which contains licenseKey, the methods are working fine. But our requirement is to perform only in one place in SecurityConfig so that all the requests can be validated.
#GetMapping(path="some/path")
public ResponseEntity<> viewDetails(HttpServletRequest httpRequest, MappingVO mappingVO) {
String licenseUser = userDetailsService.getLicenseUser(httpRequest).getUser().getEmailAddress();
....
....
}
#DeleteMapping(path="some/path")
public ResponseEntity<> deletePart(HttpServletRequest httpRequest, Part part) {
String licenseUser = userDetailsService.getLicenseUser(httpRequest).getUser().getEmailAddress();
....
....
}
In class CustomUserDetails, it has been written like this.
public CustomUserDetails getLicenseUser(HttpServletRequest httpRequest) {
String userId = httpRequest.getHeader("licenseKey");
CustomUserDetails ud = (CustomUserDetails) loadUserByUsername(userId);
return ud;
}
You should add a custom filter in the filter chain in your security config that executes before each request.
Just create a Custom Filter implementing OncePerRequestFilter.java and do the license Key validation inside of that filter. The implementation logic inside your Custom filter will run once before each request that is made on your spring boot server.
Refer
https://www.baeldung.com/spring-onceperrequestfilter
https://www.javadevjournal.com/spring-boot/spring-boot-add-filter/
If you are using Spring Security and want to filter requests to verify that it has valid token passed to it (if you're not already doing this), refer to the official documentation of your respective version of spring security to see where should you add your filter inside the filterChain.
Check Filter Ordering in:
https://docs.spring.io/spring-security/site/docs/3.1.4.RELEASE/reference/security-filter-chain.html
The token validation filter should ideally be exeucted before UsernamePasswordAuthenticationFilter.
I'm trying to configure a Spring Boot application with Keycloak to have an endpoint that is both accessible for authenticated and unauthenticated users. For authenticated users, I want to return some extra information. Here is a simple example of what I'm trying to achieve:
#RestController
public class HelloController {
#GetMapping("/")
public String index(Principal principal) {
KeycloakPrincipal keycloakPrincipal = (KeycloakPrincipal) principal;
if (keycloakPrincipal != null) {
return "Hello " + keycloakPrincipal.getKeycloakSecurityContext().getToken().getPreferredUsername();
} else {
return "Hello";
}
}
}
application.properties:
keycloak.securityConstraints[0].authRoles[0] = *
keycloak.securityConstraints[0].securityCollections[0].name = Hello
keycloak.securityConstraints[0].securityCollections[0].patterns[0] = /*
So far, I only got it to work for one of both cases. If I protect the endpoint using the security constraint above, the endpoint is only accessible to authenticated users. If I remove the security constraint, the endpoint is accessible for everyone, but then the principal will always be null.
Is it possible to achieve the intended behavior?
Have you tried something like Principal principal = SecurityContextHolder.getContext().getAuthentication();?
I believe the Principal as method parameter is only populated on secured endpoints but am unsure if it would exist in the SecurityContext. If not, you need to add a Filter to add it yourself.
I was able to solve the problem by calling the authenticate() method on the HttpServletRequest object. This will trigger the authentication process and will populate the user principal whenever possible. From the docs:
Triggers the same authentication process as would be triggered if the
request is for a resource that is protected by a security constraint.
To avoid triggering an authentication challenge, I pass in a dummy response object to the authenticate() call.
I am making service to service requests using Spring's WebClient that require an OAuth2 bearer token to be added as a header to the request. I Can do this relatively easily by creating an ExchangeFilterFunction that intercepts the request, retrieves an access token, adds it to the header, and continues on. Since this is not a user request, the SecurityContextHolder does not contain an Authentication that would hold an access token for me, so instead of retrieving from that, I would like to get an access token based on my Spring security configuration (currently defined in the spring.security.oauth2.client.registration and provider properties).
The way I'm doing this now is by Autowiring an OAuth2ClientContext and then getting the AccessToken from it. Reducing the code only to what I care about for this question, I have:
#Component
public class OAuth2WebClientFilter implements ExchangeFilterFunction {
#Autowired
private OAuth2ClientContext oAuth2ClientContext;
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
// simple retrieval of the token
String oAuth2Token = oAuth2ClientContext.getAccessToken().getValue();
// adding the token to the header of the request
request = ClientRequest.from(request).header(HttpHeaders.AUTHORIZATION, "Bearer " + oAuth2Token).build();
return next.exchange(request);
}
}
This does exactly what I want it to. However, I have recently upgraded spring-security-oauth2 to 2.5.0.RELEASE, and it is saying the OAuth2ClientContext is deprecated, but I haven't found a simple replacement for this process. So is there still a way to get an access token in a relatively simple fashion like above, and if so, how?
Also note: this concept is used elsewhere in the project and not just for the WebClient, so I'm looking to see how to properly replace an injected OAuth2ClientContext. Thanks!
Spring Security provides an exchange filter function called ServletOAuth2AuthorizedClientExchangeFilterFunction.
The ServletOAuth2AuthorizedClientExchangeFilterFunction provides a
simple mechanism for requesting protected resources by using an
OAuth2AuthorizedClient and including the associated OAuth2AccessToken
as a Bearer Token. It directly uses an OAuth2AuthorizedClientManager
and therefore inherits the following capabilities:
An OAuth2AccessToken will be requested if the client has not yet been
authorized.
authorization_code - triggers the Authorization Request redirect to
initiate the flow
client_credentials - the access token is obtained directly from the
Token Endpoint
password - the access token is obtained directly from the Token
Endpoint
If the OAuth2AccessToken is expired, it will be refreshed (or renewed)
if an OAuth2AuthorizedClientProvider is available to perform the
authorization
See https://docs.spring.io/spring-security/reference/servlet/oauth2/client/authorized-clients.html#oauth2Client-webclient-servlet for details.
Java + Spring (and Spring Security) here, interested in implementing a JWT-based auth mechanism for my web service using bearer tokens. My understanding of the proper way of using Spring Security for authentication and authorization is through the use of provided (or custom) filters as follows:
you specify which URLs in your app are authenticated (and thus require authenticated requests to access)
this is typically done in an #EnableWebSecurity-annotated web security class that extends WebSecurityConfigurerAdapter
for any unauthenticated URLs, no filters should block access to the resources being requested
an authentication filter effectively provides a "sign in" endpoint
request clients should hit this signin endpoint (authn filter) initially to obtain an auth token that can be used for making subsequent API calls
this filter should receive a type of "sign in request" object that contains a principal (e.g. username) and credential (e.g. password)
this authn filter should use the principal/credential contained in the sign in request to determine if they represents a valid user in the system
if so, an auth token (JWT, etc.) is generated and sent back to the requesters in the response somehow
else, if the principal/credential don't match a valid user in the system, an error response is returned and authentication fails
for authenticated URLs, a verification filter verifies that the request contains an auth token and that the auth token is valid (was signed correctly, contains user information such as JWT claims, is not expired, etc.)
if the auth token is valid, the request continues on to the authorization filter (see below)
else if the auth token is not valid, verification fails and the filter sends an error response back to the client
finally, an authorization filter verifies that the user associated with the valid auth token has the ability/permission to make such a request
if they do, then the request is allowed to continue on to whatever resources/controller was written to handle it, and that resource/controller provides the response back to the requester
if they don't, an error response is returned to the client
ideally the logic (code) inside this authz filter would have access to the permission annotations added to the resource method, so that I can add endpoints and specify permissions on them without having to modify the code of the authz filter
So to begin with, if anything I have stated above is a Spring Security (or web security in general) anti-pattern or is misled, please begin by providing course correction and steering me in the right direction!
Assuming I'm more or less understanding the "auth flow" above correctly...
Are there any specific Spring Security filters that take care of all of this for me already, or that can be extended and have a few methods overridden to behave this way? Or anything that comes really close? Looking at the list of authentication-specific Spring Security filters I see:
UsernamePasswordAuthenticationFilter -> looks like a decent candidate for the authn filter but expects a username and password parameter on the query string which is strange to me, and most importantly, does not generate a JWT
CasAuthenticationFilter -> looks like its used for CAS-based SSO and is not appropriate for use in non-SSO contexts
BasicAuthenticationFilter -> for HTTP basic authentication-based auth, not appropriate for more sophisticated setups
As for token verification and authorization, I (much to my surprise) don't see anything in the Spring Security landscape that could qualify.
Unless anyone knows of JWT-specific filters that I can use or subclass easily, I think I need to implement my own custom filters, in which case I'm wondering how to conigure Spring Security to use them and not use any of these other authentication filters (such as UsernamePasswordAuthenticationFilter) as part of the filter chain.
As I understand it, you want to:
Authenticate users via a username and password and respond with a JWT
On subsequent requests, authenticate users using that JWT
username/password -> JWT isn't an established authentication mechanism on its own, which is why Spring Security doesn't yet have direct support.
You can get it on your own pretty easily, though.
First, create a /token endpoint that produces a JWT:
#RestController
public class TokenController {
#Value("${jwt.private.key}")
RSAPrivateKey key;
#PostMapping("/token")
public String token(Authentication authentication) {
Instant now = Instant.now();
long expiry = 36000L;
// #formatter:off
String scope = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(" "));
JWTClaimsSet claims = new JWTClaimsSet.Builder()
.issuer("self")
.issueTime(new Date(now.toEpochMilli()))
.expirationTime(new Date(now.plusSeconds(expiry).toEpochMilli()))
.subject(authentication.getName())
.claim("scope", scope)
.build();
// #formatter:on
JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).build();
SignedJWT jwt = new SignedJWT(header, claims);
return sign(jwt).serialize();
}
SignedJWT sign(SignedJWT jwt) {
try {
jwt.sign(new RSASSASigner(this.key));
return jwt;
}
catch (Exception ex) {
throw new IllegalArgumentException(ex);
}
}
}
Second, configure Spring Security to allow HTTP Basic (for the /token endpoint) and JWT (for the rest):
#Configuration
public class RestConfig extends WebSecurityConfigurerAdapter {
#Value("${jwt.public.key}")
RSAPublicKey key;
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.authorizeRequests((authz) -> authz.anyRequest().authenticated())
.csrf((csrf) -> csrf.ignoringAntMatchers("/token"))
.httpBasic(Customizer.withDefaults())
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
.sessionManagement((session) -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling((exceptions) -> exceptions
.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint())
.accessDeniedHandler(new BearerTokenAccessDeniedHandler())
);
// #formatter:on
}
#Bean
UserDetailsService users() {
// #formatter:off
return new InMemoryUserDetailsManager(
User.withUsername("user")
.password("{noop}password")
.authorities("app")
.build());
// #formatter:on
}
#Bean
JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withPublicKey(this.key).build();
}
}
I think there's appetite to add support for something like this in spring-authorization-server to reduce the /token boilerplate, if you're interested in contributing your efforts!
I have problems authorizing users via Bearer TOKEN that I receive from Keycloak.
The task is to authorize user requests that come from an Angular application to my back-end Thorntail 2.5.0.Final micro-service. I have the front-end part covered and the application appends Authorization: Bearer {TOKEN} to every request to my service.
I have tried following these 2 guides:
https://rieckpil.de/howto-microprofile-jwt-authentication-with-keycloak-and-react/
https://kodnito.com/posts/microprofile-jwt-with-keycloak/
with thorntail microprofile and keycloak-micropfofile-jwt-fractions, but none of them seem to work.
#Inject
#ConfigProperty(name = "message")
private String message;
#Inject
private JsonWebToken callerPrincipal;
#GET
#RolesAllowed("testrole")
#ApiOperation(value = "Pridobi uporabnike", notes = "Pridobi vse uporabnike iz baze.", response = Uporabnik.class)
public Response getUsers() {
return Response.ok(callerPrincipal.getRawToken() + " is allowed to read message: " + message).build();
}
and got the following response
null is allowed to read message: Very Secure 42!
The 2. thing I tried is adding the keycloak fraction and sending the token via header following this example https://github.com/thorntail/thorntail-examples/tree/master/security/keycloak
I added the resources/keycloak.json
{
"realm": "Intra",
"auth-server-url": "https://idm.ra.net/auth",
"ssl-required": "external",
"resource": "prenosOSBE",
"verify-token-audience": true,
"credentials": {
"secret": "e9709793-9333-40a7-bb95-2026ad98b568"
},
"use-resource-role-mappings": true,
"confidential-port": 0
}
and the KeycloakSecurityContextFilter.java from the example.
If I try to make a call to my endpoint I get 401 Unauthorized or 403 Forbidden if I don't send a token with my request.
So what I want to know is which fraction is meant to be used if my task is to authorize users via Bearer token on my Thorntail microservice?
microprofile-jwt, keycloak-microprofile-jwt or keycloak and what is the minimal required configuration for it to work?
The keycloak fraction is the Keycloak adapter for WildFly per https://www.keycloak.org/docs/4.8/securing_apps/index.html#jboss-eap-wildfly-adapter It lets you use the common security mechanisms from Java EE (<security-constraint>s in web.xml etc.) You can see an example here: https://github.com/rhoar-qe/thorntail-test-suite/tree/master/wildfly/keycloak
The microprofile-jwt lets you use bare MicroProfile JWT (that is, #RolesAllowed on JAX-RS resources, etc.). You have to configure the expected issuer, its public key etc., as described in MP JWT documentation. You can see an example here: https://github.com/rhoar-qe/thorntail-test-suite/tree/master/microprofile/microprofile-jwt-1.0
The keycloak-microprofile-jwt is a bit of a mix. It doesn't expose the Keycloak adapter, but uses it internally to validate tokens issued by Keycloak, and exposes the tokens via MicroProfile JWT. You can see an example here: https://github.com/thorntail/thorntail/tree/master/testsuite/testsuite-keycloak-mpjwt