Spring Security returning 403 with correct username password - spring

I'm trying to enable basic http authentication with a single static username password for the whole project. I have tried many things but none have been successful. This is the latest method that I am trying
My security configuration
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").hasAnyRole().and().httpBasic();
}
}
My application.properties
spring.security.user.name=myusername
spring.security.user.password=mypassword
When I go to one of my controllers I do get the username/password dialog. However if I enter the correct one I get a a page with the message
My Whitelabel Error Page
There was an unexpected error (type=Forbidden, status=403).
Forbidden
and in my spring logs I see
Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [150,084] milliseconds.
When I enter a wrong username password, the auth dialog keeps refreshing, so I am sure I am entering the correct username pass, and Spring is verifying that. But I don't understand why I get a 403 error when the page loads.

Related

SpringBoot works on the web but doesn't work in the postman?

I'm trying to build to build a really basic user/role CRUD with spring security.
I created 2 types of accounts: admin and user.
After I go to this URL: http://localhost:8080/api/v1/employees first I get login and after that I get the result
The problem start when I try to connect via postman. I can't get past the login.
I can't get past the login no matter what. I tried other controller but the same thing happens.
Am I doing something wrong? Am I missing a step?
To make a call in Postman, you need to pass a proper authorization (token header/cookie) when calling an endpoint. In your current case, Postman either shows you a login page which is that HTML you see, or an error page because unauthorized
I had this problem yesterday, it's most likely the same thing.
I disabled csrf in the class that extends WebSecurityConfigurerAdapter to get it to work. If you're moving into production, you should probably leave it enabled.
My WebSecurityConfig class:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/").permitAll();
}
}
I don't fully understand how the csrf protection so there might be issues if you try to log in from a browser. Uncomment out the .csrf().disable() when you want to run in from a browser

Spring Security Basic Auth Password Rotation Issue

Experts,,
I have a spring boot 2.5.5 application(embedded tomcat) where I have to configure the basic auth.
This is the class I have that does the work for me
#Component
#EnableWebSecurity
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
}
The issue is I just need to enter the user/password once in the browser and it works for any subsequent request. Furthermore, I don't need to supply the new username/password after the server restarts which is driving me crazy - the app still works and I can access my APIs/pages.
Even if i assume the browser is somehow saving the username and password it should not work once the server is restarted as the password gets changed - isnt it ?
Update II:
Following the advice from M. Deinum I made the session stateless and it worked. I then went on to implement Basic Auth with InMemoryUserDetailsManager and added the below code and we are back to the same issue again. The credentials seem to be again stored in session and I need not pass them for the subsequent request.
#Autowired
public ApplicationSecurityConfig(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
#Override
#Bean
protected UserDetailsService userDetailsService() {
UserDetails user = User
.builder()
.username("admin")
.password(passwordEncoder.encode("admin"))
.roles("ADMINISTRATOR")
.build();
return new InMemoryUserDetailsManager(user);
}
This is how I would expect it to work with your current configuration.
When successfully authenticated with basic authentication the browser will send the username/password for all other subsequent requests. So this is as expected.
Another thing is that, by default, Spring Security will use the HTTP Session to store the user information. A session-cookie is also sent with each request so that the session state can be restored for each request.
This session state is, by default for your servlet container, saved to disc when you stop the server, when you restart and the session is still valid (not timed out) it will still have the authentication.
You can fix this by making Spring Security not use a session (set the session mode to stateless).
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
The drawback of this is that it will re-authenticate each request (which takes some time and thus impacts your performance slightly). But it should give an error after restart now, as you changed the password.

Preventing need to re-login with Angular6/Spring Boot 2 web app using oauth2

I'm writing a small web-app using Spring Boot 2 as the backend and Angular6/Ionic as the front end. The intention is to have users add the site to their home screen and for it to basically look/feel like a native app. This is working pretty well but I would like to use Google for login with Spring Security Oauth2. My problem is that Spring Boot keeps the user auth tokens on the server associated with the session, and the IOS home screen icon loads with all cookies cleared every time the icon is clicked. Since the cookie is gone when the page loads, the user needs to log in again.
Apparently html5 local storage should persist from launch to launch, so I'm thinking I need generate a key for the user after auth which can be stored in in local storage on the device, then when the the user accesses the page it can provide this key which I can use to "Authenticate" them on the server... something along those lines.
I'm looking for ideas of how to allow the user to stay "Logged in" without the availability of cookies being reliably stored for any length of time.
Currently Using
Spring Boot 2
Angular 6
Ionic 4
Spring Security
Spring Oauth2
Everything is behind security except for the login page.
At the moment I'm persisting sessions to jdbc and my configs look like this:
applicaion.yml
spring.security.oauth2.client.registration.google.client-id=XXXXX
spring.security.oauth2.client.registration.google.client-secret=XXXX
server.servlet.session.persistent=true
spring.session.store-type=jdbc
spring.session.jdbc.initialize-schema=always
MvcConfig.java
#EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("/static");
registry.addResourceHandler("/static/*.js", "/static/*.css", "/static/*.svg")
.addResourceLocations("/static")
.setCacheControl(CacheControl.maxAge(365, TimeUnit.DAYS));
}
}
SecurityConfig.java
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2Login().and().logout().logoutSuccessUrl("/");
}
}
I've tried telling spring to put session ID's as x-auth headers, but google oauth appears to stop working then. As in I go to a page, get the screen to click on to log in with google, log in with google and am returned to my login page with an error: "Your login attempt was not successful, try again."
So basically google oauth works with config above but fails with this added to SecurityConfig.java
#Bean
public HttpSessionIdResolver httpSessionIdResolver() {
return new HeaderHttpSessionIdResolver("X-Auth-Token");
}
This is apparently failing because The appropriate session information isn't getting passed to/back from Google. My login process produces 3 "sessions"
1) When the user first tries to access the page and gets the login page
2) When the token response is returned from google. This session indicates an error of "authorization_request_not_found"
3) When the user is re-directed back to the login page.
It looks like some info about the session is being passed to/back from google but the session ID's doing look right
Request to google auth is:
https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=1111111111111-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com&scope=openid%20profile%20email&state=NGW6kTxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%3D&redirect_uri=http://localhost.com:9733/login/oauth2/code/google
Callback from google auth:
http://localhost:9733/login/oauth2/code/google?state=NGW6kTxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%3D&code=4/xxxx_xxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&scope=openid+email+profile+https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/plus.me+https://www.googleapis.com/auth/userinfo.email&authuser=0&session_state=6ee92xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx..2618&prompt=none

Unable to Authenticate a User with an LDAP Server using LDAP User Search Query with Spring Security

LDAP Server Hierarchy as retrieved via Apache Directory Studio:
Root DSE:
DC=company,DC=com
OU=Offices
OU=Region Offices
OU=Region1 Office
OU=Users
CN=Jayesh Mulwani
WebSecurity is enabled as a part of below class:
public class LDAPSecurityConfig extends WebSecurityConfigurerAdapter{
protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.ldapAuthentication()
.contextSource().url("ldap://server-url/CN=auth_support,OU=Misc,DC=company,DC=com")
.managerDn("username").managerPassword("password")
.and()
.userSearchBase("OU=Offices,DC=company,DC=com")
.userSearchFilter("(&(objectClass=user)(cn={0}))");
}
}
Once the application is setup on tomcat, i enter the username along with its password but the authentication fails and no error is prompted.
Can someone please assist me with the approach or specify if i'm missing something here ?
I have fixed the problem by adding the below two conditions
.groupSearchFilter("(&(objectClass=group)(AccountName={0}))")
.groupSearchBase("CN=DEPT_All_Employees,OU=DepartmentSecurityGroups,OU=Resources,DC=company,DC=com")
I referred this example to fix the issue http://www.jcombat.com/spring/spring-security-ldap-authentication

Issue with the spring security tutorial on spring.io

I am trying to run the spring security application on the official website. When I try to access the context root I get the user authentication prompt even though .antMatchers("/", "/home").permitAll() allows all access to /home and /. Also the password is being set in the application in the following code
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
However I still get the Using default security password message in the logs with the password mentioned. Please could you help.
Edit:
I had made a mistake in the code, I forgot to annotate the WebSecurityConfig class with #Configuration and #EnableWebSecurity annotations.
The password which you find from log is from basic auth which is by default enabled, you can do httpBasic().disabled() to disable it, then you will not see the default password any more.
Update
I saw you are using spring-boot, which makes live much easier, try add this property: security.basic.enabled=false, it should help you to disable it..

Resources