Spring OAuth2 explain Authorization server configuration - java

I am trying to implement OAuth security and met a problem that for me is not clear enough configuration class.
While implementing AuthorizationServerConfigurer i have three configurers:
ClientDetailsServiceConfigurer used to provide the way how and from where to get client details. As an example, it can be service which provides registered clients from the database.
When it comes to AuthorizationServerSecurityConfigurer and AuthorizationServerEndpointsConfigurer I am not sure what they do or how they should be configured. In the documentation it said only:
AuthorizationServerEndpointsConfigurer: defines the authorization and
token endpoints and the token services.
Maybe someone can explain in simple words what these two configurers do, or what they are used for.

AuthorizationServerConfigurer's javadoc is more informative than the linked documentation. AuthorizationServerSecurityConfigurer, as its name suggests, configures the security of the Authorization Server itself. For example you can override the OAuth endpoints security such as /oauth/token, provide an access denied handler or restrict to SSL access. Here are what the documentation says about it:
Configure the security of the Authorization Server, which means in
practical terms the /oauth/token endpoint. The /oauth/authorize
endpoint also needs to be secure, but that is a normal user-facing
endpoint and should be secured the same way as the rest of your UI, so
is not covered here. The default settings cover the most common
requirements, following recommendations from the OAuth2 spec, so you
don't need to do anything here to get a basic server up and running.
As for AuthorizationServerEndpointsConfigurer:
Configure the non-security features of the Authorization Server
endpoints, like token store, token customizations, user approvals and
grant types. You shouldn't need to do anything by default, unless you
need password grants, in which case you need to provide an
AuthenticationManager.
Here is a sample from one of my projects:
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.authenticationManager(authenticationManager)
.tokenStore(jwtTokenStore())
.tokenEnhancer(tokenEnhancer());
}
Here I provided a JwtTokenStore as my TokenStore and a AuthenticationManager since I was using Password Grants.

I am using spring-security-oauth, there is a helpful documentation maybe help you :
projects.spring.io/spring-security-oauth/docs/oauth2.html

Related

How to implement role based authorization on resource server with new Spring Authorization Server

I am trying out the new Spring Authorization Server, and I have hit a dead end in my endless googling.
Without the #Secured and #EnableGlobalMethodSecurity configured, it works like a charm, but the moment I try to secure the resource server with the above annotations I now get a 403 Forbidden error.
Authorization Server Configuration
DefaultSecurityConfig.java
MongoDBUserDetailsService.java (User Detail Service)
The roles are in the format of "ADMIN" without the prefix "ROLE_" since its already added during runtime.
Resource Server Configuration
ResourceServerConfig.java
ArticlesController.java
I kinda figured out a way to do it, which was to implement a custom converter for my jwt token, where I then can query the user and their roles from db using the claim from token and then injecting that to the request filter.
CustomJWTAuthenticationConverter
ResourceServer SecurityFilterChain

Java Spring MVC Auth0 SSO not getting tokens (no Spring Boot)

I'm trying to get SSO up and running. So when I sign in on a different application (on the same auth0 domain) and go to the login page of my application I want my application to automatically log me in.
I managed to get the first parts running and I received an authorization code from auth0. But when I try to retrieve the tokens they are all null.
my redirectuUri and clientSecret are correct and I assume the authorization code returned earlier is correct aswell.
It seems as if the request doesn't return any tokens. They are all null.
Where do I start to find out what's going wrong? Thanks!
public Tokens getTokens(final String authorizationCode, final String redirectUri) {
Validate.notNull(authorizationCode);
Validate.notNull(redirectUri);
System.out.println("Sending request with code to retrieve tokens.");
final Credentials creds = authenticationAPIClient
.token(authorizationCode, redirectUri)
.setClientSecret(clientSecret).execute();
return new Tokens(creds.getIdToken(), creds.getAccessToken(), creds.getType(), creds.getRefreshToken());
}
If using the Auth0 Spring MVC Library (not Spring Security MVC) - then best place to stick a breakpoint would at the top of the Callback Controller's handle method
You can then step through / step in - and inspect what is going on. This method calls getTokens and that delegates to Auth0ClientImpl which is the code block you reference in the question.
Check your ClientId, ClientSecret and Domain are all correct - and if your code is reaching this method - that the code / redirectURI being passed in are also correct. Would check the Auth0 logs from the Dashboard too, and determine if any successful authentication events are recorded.
Finally, please can you confirm which version of auth0-java (maven POM dependency / gradle dependency) you are using - and which version of the auth0-spring-mvc library you are referencing also.
For SSO Specific Examples - plain Spring falls between two stools as I wrote one for plain java and one for Spring Security MVC - but you should get a good idea of what is going on by studying these two samples:
Auth0 Servlet SSO Sample
Auth0 Spring Security SSO Sample
In particular, study the JSP pages since that is where the SSO checks and auto-login logic lives. Ensure too that you enable SSO on the Settings of each of your Clients defined in your Auth0 tenant.
Disclaimer: am the author of the above libraries - please leave me comments below if you still have problems and require any clarifications.

Securing a jersey RESTful web service

I'm developing a restful web service that will be consumed by an Android application later on.
Right now, I'm seeking a way to secure the access to my resources:
I found several ways for implementing that on the net, but I can't figure out what is the most appropriate one.
For example, I found that Oauth specifications are more convenient for third-party applications which is not my case.
So what are the most suitable ways for securing jersey APIs, and I'll be glad if someone can provide me with any tutorials/documentations on that.
I'm using a Glassfish v4 server and the Jersey JAX-RS implementation.
After looking at different options I used an authentication filter and basic auth. Very easy to implement.
Some example code:
You need a filter
public class AuthFilter implements ResourceFilter, ContainerRequestFilter {
...
}
And a security context:
public class MySecurityContext implements SecurityContext {
...
}
And a user class:
public class User implements Serializable, Principal {
...
}
Finally, you can add the filters you need like so: (pass your ResourceConfig object to this function)
private void prepareFilters(ResourceConfig rc) {
rc.getProperties().put("com.sun.jersey.spi.container.ContainerRequestFilters",
getClassListing(new Class[]{
AuthFilter.class
}));
rc.getProperties().put("com.sun.jersey.spi.container.ContainerResponseFilters",
getClassListing(new Class[]{
CORSFilter.class, //You might not need this
GZIPContentEncodingFilter.class //You might not need this
}));
rc.getProperties().put("com.sun.jersey.spi.container.ResourceFilters",
getClassListing(new Class[]{
RolesAllowedResourceFilterFactory.class
}));
}
BTW, you can add #Context SecurityContext securityContext; to your resource class(es) or the individual methods for more fine grained access control. The SecurityContext will be injected into the context of your resource so you can access the User object per request with
With this setup you can annotate your REST methods with #PermitAll, #RolesAllowed, etc which gives you a good level of control over your RESTful interface.
I just finished my stateless (without sessions) user auth and management with Jersey.
Let me know if you want a full example or if you want to give it a try yourself ;)
The simplest way would be using the Java EE build-in Container Managed Security model to secure your rest resources as described in this tutorial. It allows you to configure the security based on users and roles stored in a database or file realm in the web.xml or the the classes themselves.
The disadvantage would be that you must start a session, extract the JSESSIONID and send it in each of your requests so that the server can verify it, but that makes your services more 'stateful' and violates the statelessness of the rest architecture.
Another way would be implementing custom security by using WebFilters, like sending the user name and password with each of your requests and verity them based on the information in a special db. If the information doesn't match the information stored in the database a redirect or a special error code can be returend in the Response object.
The best approach I think is using OAuth2 as described in this specification. Dependend on what kind of client you are using (desktop, web page, mobile client) there are different workflows and apart from that lots of benefits like creating tokens for special scopes of your application (read-only or full access,...). Google provides many different apis that can be accessed by the same account. If an applications only needs data from the calendar api, the requested token only gives you access to this special api and not to the entire resources of the account (like mail data, notes, etc). Another point would be that the security handling is decoupled from the client and no password must be stored in the client application.
You can either implement everything on your own or use a open source project like this. It provides a description on how it works and the code is very good but it has many dependencies to spring frameworks. For my use case I've startend replacing them by vanilla Java EE 7 code and create a solution based on the idea of this open source project. The reason behind the replacements was that it's more future-proof and it avoids class loader problems during the deployment.
In the Android app a Authenticator can be implemented for secure storing of the token.

Token Based authentication in Spring

We have a Spring web application which already uses Spring security for authenticating users and granting access to a group of restricted pages. However we have another group of resources that we wish to secure. For this second group we don't want user authentication but instead we want users to go a page: /access.html and enter an access code (previously emailed to them) and then they will be granted access to those resources without login. The access code (token) will only be valid for a limited period of time and then it expires.
Can I use spring security somehow to implement this in parallel to the user authentication setup we already have in place?
Sure, there are a couple of ways to do this. It sounds like all you need to do is create a filter that can check for your token in the session/request and create/update the Spring Security context to have the desired role. Then authorization proceeds as normal.
In particular you will be adding GrantedAuthories to your Authentication object for the Spring Security Context. There are a lot of details to this process and I admit my answer is not complete but a full answer would be pretty extensive.
I have done the similar things with cookie.
You can implement your own filter which extends GenericFilterBean
And then set the config with spring-security like below
<security:http ... >
....
<sec:custom-filter position="FORM_LOGIN_FILTER" ref="cookieAuthenticationFilter" />
</security:http>
Have a look at the source code of BasicAuthenticationFilter may be helpful.

Spring Boot Security and Auth0 - Cannot disable CSRF

I am building a RESTful Spring Boot and React/Alt application. I want to add spring security to make sure that there could be no unauthenticated requests to the API.
I am using Auth0 for an authentication provider so users can log in to the application and more specifically the spring-security-auth0 library to handle the server side security side of things.
https://github.com/auth0/spring-security-auth0
After following the basic tutorial on Auth0, I have configured the security config in my spring application so that requests to the API will not work without a JSON web token. This works, but there are some endpoints (those that need a POST) in the controllers that don't. I get this error in Chrome devtools -
Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'
I understand that there are no CSRF headers present and that is why it isn't working. But the main reason I am confused is because I have disabled CSRF and it still happens. As the spring docs instruct, I've done this -
#Configuration
#EnableWebSecurity
#ComponentScan("com.auth0")
#ImportResource("classpath:auth0-security-context.xml")
#PropertySource("classpath:auth0.properties")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
I don't need CSRF in this case as the app will only ever be used in a dev environment. Why does this still happen even though I have disabled CSRF completely?
The CsrfFilter that is responsible for the Exception is definetly enabled.
This can have various reasons. Can it be you have another instance of WebSecurityConfigurerAdapter configured somewhere ?
You can try the following :
Set a breakpoint in line 'http.csrf().disable();' to see if its really executed.
Set breakpoints in the constructor(s) of WebSecurityConfigurerAdapter to see whether many instances are created.
This should show you whats going wrong..

Categories