Bypassing Full authentication is required - Spring - spring

I have an issue. I built a Spring(+REST, AngularJS, Java and that's about the most important technologies used) application(using JHipster), but I have some difficulties testing it. I try to run requests using Postman(http://localhost:8080/api/users, for example, which is a URI generated by default when you build your JHipster application), but I get the "Full authentication is required to access this resource error". Now I imagine that this could be bypassed by using some sort of token, but I was wondering if there was something I could do to get rid of this. I mean, for example, if I wanted http://localhost:8080/api/users to be accessible without having to log in, you know, display the whole list of users on a website page to everyone, not only to those that have an account, what would I need to do?
Thank you

If you use microservices with JHipster, each microservice has MicroserviceSecurityConfiguration. There you have an overriden configure method which usually has a part like:
.and()
.authorizeRequests()
.antMatchers("/api/profile-info").permitAll()
.antMatchers("/api/**").authenticated()
You can define /api/users similar to api/profile-info. You can also play with permissions in this file and so on.
And something like this surely exists for a monolith app.

Related

Authentication system in frontend - backend services

I'm very new in Spring and never really used java for making web. And I'm making a web with a separated frontend and backend services and I'm trying to make an authentication system using Spring Boot Security. How can I do it? Do I put the security on both the service or just one of them? What's the best way to implement it?
The question is subjective and can have too many interpretations based on context. My understanding is that putting security on both front-end and backend is the best way to implement. After a successful backend authentication you should issue a unique cookie to the browser as it allows users to continue using a site without having to log in to every single page. For each subsequent call, the website recognizes the user from cookie data.
You can use this link for a better understanding of dual authentication mechanism.

Spring Security + JWT: How to enrich Authentication/Principal after successful login?

I’ve got a question which seems popular, but I couldn’t find the answer. Well there’s a lot of information about it but I’m not sure what the best way is. So here’s the scenario.
We have a Single Page Application (SPA) and a RESTful Web Service (API). We use an external authentication/authorization service provider via OAuth2/JWT. But I need to persist the user ID (provided by the external authentication provider) on the database on the server side after successful login. And also I need to enrich the Authentication/Principal object in security context after successful login (for example by adding email).
There's a lot on the web about this scenario. But we have SDK for authentication/authorization already and it works perfectly (no custom code, etc). I just need to add something to the authentication object. What is the correct way to do it? Thanks.
For the record, this is what we did:
As I said there's already a SDK doing all the heavy lifting of authentication mechanics. We just need to enrich the authentication object after successful authentication. So we wrapped the AuthenticationProvider (implemented in the SDK) in our implementation (inspired by PreAuthenticatedAuthenticationProvider) and after successful authentication, we enriched the result using our UserDetails implementation (inspired by PreAuthenticatedGrantedAuthoritiesUserDetailsService). The rest was straight forward.
PS: please let me know if you don't like the idea.

Spring Security Kerberos SSO for a REST API (Tomcat)

Here is my problem:
Context :
-Windows Server 2012 with ActiveDirectory
-Tomcat
-Rest API (Spring)
I'm currently trying to restrict REST request. I want that only specific groups of the AD could access to specific resources. I'm restricted to Kerberos authentication.
System configuration
Create a user in domain "Tomcat"
setspn -a HTTP/apirest.domain#DOMAIN
Generate a tomcat.keytab using ktpass
API rest configuration
I'm using the spring security sample on github that you can find here :
https://github.com/spring-projects/spring-security-kerberos/tree/master/spring-security-kerberos-samples/sec-server-win-auth
I know that there is an EntryPoint and this is not needed in my context (API Rest). I've chosen this sample because it seems to use the windows authentication context and use it to automatically authenticate me in the spring security context. Right after, an ldap request is send to extract all information about the user logged. In my case, I need to extract the group.
I'm also using :
https://github.com/GyllingSW/kerberos-demo
To extract the role of the user with the class "RoleStrippingLdapUserDetailsMapper.java" instead of the "ActiveDirectoryLdapAuthoritiesPopulator". This implementation also offers localhost authentication but the issue with the NTLM token seems to be fixed in last commit of spring security.
I'm not really sure if this is the right way to do what I want.
My authentication seems to fail and I only have one things going wrong in my logs..
"Property 'userDn' not set - anonymous context will be used for read-write operations"
Questions
Do I have to run my tomcat service using the tomcat account ? (Seems to be, yes)
Am I doing the right things with Kerberos security ?
How can I get rid of the anonymous context?
The anonymous context seems to be set just right after Tomcat start. I want to get a context just after that my user (For instance, user1) requests the rest API (EntryPoint or whatever)
If there is something unclear let me know, I will try to reformulate!
Thanks,
You do not need to query LDAP to get information about which groups does user belong to. Active Directory already adds this information to the Kerberos ticket which is sent from browser to Tomcat.
You just need to extract this information from the token for example using Kerb4J library. It comes with Spring integration inspired by spring-security-kerberos project so it should be pretty easy to switch to it.
If you still want to query LDAP you need to authenticate in LDAP before you can make any queries. Again there's no need to use end-user accounts for it - you can use the keytab file for Kerberos authentication in LDAP and query groups using "Tomcat" account
I found a way to fix my issue.
In a REST API context, you have no entry point. I tried to set my entry point to an unmapped URL, just to do the negociation. By doing this, you will receive an HTTP response with the error code 404 (Not found) but with the right header was added by spring security (WWW-Authenticate).
The web browser will not send the ticket service if the error code is not 401.
To solve this problem, you have to create a CustomEntryPoint class (implements AuthenticationEntryPoint) and you need to override the "commence" method to return a 401 HTTP code with the right header.
I hope that could help. If there is a better way, let me know !

Spring SSO and account creation

So I'm working on a university project in which my group needs to create an android application that talks to a backend build with spring. So far we've been using JWT's for user authentication/authorization and everything was fine and dandy. However, our client wants to have single sign-on with Google and Facebook and of course to still be able to create an account, just like this form (but on android, not a browser).
I have spent the last month researching and googling how to do this and especially how it's supposed to integrate with the android app. I feel like I'm missing a key point because I see this everywhere, so I assume that is not that hard to do. As much as I understand, I can have two endpoints: login/google, login/facebook to get authorised with their authorisation server. That I have, I followed this guide and I understand 70-ish% of it.
Then my idea is to have users that are logging in for the first time to be saved in our database. I'm not entirely sure how to do that (because I'm not entire sure how the SSO spring code works..). My main questions tho are:
How to have both social login with google/fb and the ability to make an account/login with credentials.
If the user was to make an account, do I have my own authorisation server where I store credentials or do I manage that on the main server.
How do I handle that from the android app? Do I store the refresh token or do I do something else?
There are a couple of things
You want to integrate with spring-social for any social providers such as google/fb. Add the dependency and configure by following the tutorials
See https://github.com/spring-projects/spring-social/wiki/quick-start
If you also want users to create their own account, u do not need an authorization server. What u need is spring security vanilla form setup with a configuration
Something like
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage("/login/")
.loginProcessingUrl("/j_spring_security_check")
.usernameParameter("j_username")
.passwordParameter("j_password")
.successHandler(authenticationSuccessHandler())
.failureHandler(authenticationFailureHandler())
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessHandler(logoutSuccessHandler())
.invalidateHttpSession(true)
}
Yes but i recommend u find an oauth library you can just plug in.. and hopefully it will handle the refresh_token logic for you.. you should not need to implement these things yourself.
I hope this helped some, these questions you asked are very broad.. but hopefully it will get you somewhere.

Spring Boot Admin: 401 on Jolokia endpoint causes authentication to fail

I am using Spring-Boot-Admin in order to monitor a SpringBoot app whose actuator endpoints are secured using basic auth. The required credentials are transferred to Spring-Boot-Admin (SBA) like described in the documentation. SBA itself is also secured using spring-boot-admin-server-ui-login and the provided SecurityConfiguration (based on the documentation & sample apps, see Github Repo for code).
Both the app to be monitored and SBA are deployed via docker.
Logging in to SBA works fine and I can see the application state as well as the health results. For some content I see a nested login mask though. When I click on "Logging" or "JMX" I am redirected to the login mask:
In the browsers network tab I can see that a 401 is returned for the /jolokia endpoint. All requests after that seem to be forwarded to the login page.
I have the following questions:
Why am I logged out if one request to the application fails? Is that a bug?
What is the source of the 401? SBA or my app? I know that SBA proxies requests to the app. According to the access logs from my app no request to /jolokia is done when I login to SBA. Does this mean that the 401 is returned by SBA directly? Its logs contain nothing of relevance though.
Accessing the /jolokia endpoint directly works fine. It even works when I use the same (proxied) URL that SBA uses (e.g. http://XXX:8090/api/applications/XXX/jolokia/). What is different when this is executed from within SBA?
I've tried to find more error details in SBA but so far failed to find the proper logging options. They either contain nothing relevant or way too much information (e.g. Spring Security) that doesn't seem to be relevant. Logging the full response would probably help...
Edit: I just realized, that the request to the /jolokia endpoint actually contains a different cookie (Cookie:JSESSIONID=4E51B84AE15A6890500F967B23EB92AC) than the requests to the working endpoints (e.g. /metrics). Thats weird, but probably explains why the /jolokia endpoint returns a 401. Now the question is: Why does it send a different cookie`?
I tried various things, but in the end couldn't solve this.
I instead ended up with a different configuration: No security at all for the endpoints (management.security.enabled=false), but exposing them on a different port (management.port=8081). This management endpoint is blocked for external access to the system completely.
With that, SBA behaves nicely and the application is still secure. In the end, its a much simpler setup which is good, too.
I had a similar problem.
I could access all actuator endpoints, but everything with /jolokia would not be authorized. Although my security setup is a different to yours, i assume the problem is the same.
When i digged into this I found out that jolokia runs in its own servlet separately from the spring boot application. Maybe therefore you have different sessions!?
My Security Config tries to match this expression
.mvcMatchers("/actuator/**").access("hasAnyRole('ADMIN','SBA')"),
but the SBA user role was not able to access Jolokia. It always matched the last fallback-rule where only Admin was allowed.
In my case the context- and servlet-path of the jolokia servlet would be stripped away from the request path before trying to match it to my security config. Then it would only match "/list" against my MVC matchers instead of "/actuator/jolokia/list" which would then not fit as expected.
Unfortunately I do not have a fix for your problem. For my case i added a requestMatchers rule which is a little bit less opinionated and would still match:
.requestMatchers(request -> request.getRequestURI().contains("/actuator/jolokia/")).access("hasAnyRole('ADMIN','SBA')")
instead of
.mvcMatchers("/actuator/**").access("hasAnyRole('ADMIN','SBA')")

Resources