Spring Security - configure HttpSecurity - java

I'm new to Spring Security, I'm trying to create a login form with Spring Security.
This is the required scenario:
1) users log into the app with username - password (please note that I'm using the default loginpage provided by spring Security)
2) if the login is OK, the user go to eventList.jsp
3) if the login is KO (wrong credentials) an error is shown
My WebSecurityConfigurerAdapter configurations:
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("amdin").password("111111").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().defaultSuccessUrl("/eventList");
}
Error 1: if I insert the right credentials I don't see /eventList, but i receive a 404 (/spring-security-helloworld-annotation/WEB-INF/pages/login.jsp). Why I am not redirect to /eventList? (pheraps because /eventList accept only GET in my RequestMapping annotation?
#RequestMapping(value = {"/eventList"}, method = RequestMethod.GET)
Error 2: if I try to "manually" go to /eventList, by adding "eventList" to the end of the URL in my browser, I can access to the requested page without performing the login operation!!! THe only URL that I want to be accessible without performing the login operation is the login page itself!!!
The line.anyRequest().authenticated() should not allow all this!!!
How could I obtain what I desire?
TY in advance

The correct security chain looks the following:
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/eventList")
.permitAll()
.and()
.logout()
.permitAll();
you forgot the permitAll() statement as well defining the loginPage()
Hope it helps! Drop me a pm if you need further help with it.

Related

How to allow guest to access home page without login in Spring Security

I want that the home page and other pages be accessible for everyone without login in Spring Security. I used this code but it forces me to login. This is the code:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/secure**").hasAnyRole("ADMIN","USER")
.anyRequest()
.authenticated()
.antMatchers("/home**").anonymous()
.and()
.formLogin().permitAll();
}
I enter localhost:8080/ but it redirects me to /login
Add .antMatchers("/").anonymous()
.anyRequest().authenticated() means that the user must be logged in, i.e. not anonymous, but with no specific role requirement.
You can combine them, e.g. .antMatchers("/", "/home**").anonymous()

An unknow login page show up

I am trying to understand this spring-boot project:hbs-spring-boot-jpa-mysql-thymeleaf-security
In the HbsController the code is
As I know when I input the localhost:8080/hbs, I should see the index page right? but I can only see thisAnd I look into the project I can't find the login page? where is it? please help me.
in the SecurityConfig you might have the /hbs mapping with authorisation required.
in this example from https://www.baeldung.com/spring-security-login
#Override
protected void configure(final HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/anonymous*").anonymous()
.antMatchers("/login*").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/perform_login")
.defaultSuccessUrl("/homepage.html", true)
//.failureUrl("/login.html?error=true")
.failureHandler(authenticationFailureHandler())
.and()
.logout()
.logoutUrl("/perform_logout")
.deleteCookies("JSESSIONID")
.logoutSuccessHandler(logoutSuccessHandler());
}
".antMatchers("/admin/**").hasRole("ADMIN")" forces the acces to only "ADMIN" users and redirects them to /login
try to modify your configuration class that implements WebSecurityConfigurerAdapter and it will work
I think it is because there is spring boot security implemented/included in the pom file/project: https://spring.io/guides/gs/securing-web/
You can see the spring security configuration in the class "SpringSecurity.java" in the folder "security". You can modify it there or look up what the credentials are.

Spring boot authentication issue - always redirected to /login

I have troubles with Spring Security. I want to override the built-in /login endpoint from spring in order to be able to load mylogin.html page which is located under resources/templates/mylogin.html. I think that this issue comes from the below code. Also, the class is annotated with #EnableWebSecurity.
The security bean configuration from my project:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
//The pages does not require login
http.authorizeRequests().antMatchers("/","/welcome","logout").permitAll();
// /userInfo page requires login as ROLE_ADMIN, ROLE_DOCTOR, ROLE_PATIENT
http.authorizeRequests().antMatchers("/userInfo").access("hasAnyRole('ROLE_ADMIN','ROLE_DOCTOR','ROLE_PATIENT')");
//For ADMIN only
http.authorizeRequests().antMatchers("/admin").access("hasRole('ROLE_ADMIN')");
http.authorizeRequests().and().exceptionHandling().accessDeniedPage("/403");
//Config for Login Form
http.authorizeRequests().anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/mylogin.html")
.permitAll(true)
.and()
.logout()
.logoutSuccessUrl("/mylogin.html?logout")
.permitAll();code here
}
Is someone who can help me?
I advise you to use spring-boot-starter-thymeleaf library. You can do
.loginPage("/login")
Then with Spring Controller, you can catch the /login request in a method. In this method, return "mylogin" will redirect user to the mylogin.html page.
Example here: https://github.com/cihangir-mercan/spring-boot/

Spring boot stateless form login /oauth/authorize

Is it possible to create a form login page, where the session creation policy SessionCreationPolicy.STATELESS.
When I configure it without sessionCreationPolicy, the login works.
#Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.csrf().disable()
.and()
.authorizeRequests().anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll();
// #formatter:on
}
}
When logging in, the POST will be send to /login and apperantly it will look in the session to redirect it back to the /oauth/authorize page (if you were coming from there).
But when I add:
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
It does not know where to redirect it to after login. Does anyone know how to achieve this?
I could not make this work with the .formLogin() options.
What I did is create a new MVC controller, where you could post your username and password. Authenticate against AuthenticationManager, if login was successful, forward the request to where /oauth/authorize is locating.

How to get URL hit by user in Spring security config file

Im working in a java-springs web application with custom security evaluator method,
i need to pass the URL hit by user as a parameter for the method permissionEvaluator.canUserAccessPage(URLHitByUser).
How to get URL hit by user.
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
//.antMatchers("/view/**").permitAll()
.antMatchers("/assets/**").permitAll()
.antMatchers("/view/admin.html").access("#permissionEvaluator.canUserAccessPage(URLHitByUser)")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").usernameParameter("username").passwordParameter("password")
.defaultSuccessUrl("/index")
.permitAll()
// [...]
}
If you intention is controlling the access to certain roles,this can be achieved by using sec:intercept-url in applicationContext-security-preauth.xml.
Thanks

Categories

Resources