I'm trying to add spring security to a custom Java project, by manually adding all dependencies etc. So far I've been successful, but I (think I) have a problem with my WebSecurityConfigurerAdapter:
#Override
protected void configure(HttpSecurity http) throws Exception{
http.authorizeRequests()
.antMatchers("/index.html").hasAnyRole("USER", "ADMIN")
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.formLogin()
.loginPage("/sign-in")
.permitAll();
}
When restricting index.html as above, the user is immediately required to login when entering the application base-URL (e.g localhost:8080/myapp/). However if I change the antMatcher to:
...
http.authorizeRequests()
.antMatchers("/test**").hasAnyRole("USER", "ADMIN")
.and()
...
I can hit the application base-URL without having to login. It's worth mentioning that index.html and test.html are completely identical (they only contain an h1-tag), and are both located in the root of the generated .war-file:
enter image description here
How do I configure the application so that the user doesn't have to login when entering the base-url, but only when requesting the index.html (e.g. localhost:8080/myapp/index.html)?
Thanks in advance
Edit: My app has an endpoint at localhost:8080/myapp/ looking like this:
#GetMapping("/")
public String home() {
return ("<h1>Welcome</h1>");
}
The idea is that the user should be able to reach this without having to authenticate.
You can try this...
'''
http.authorizeRequests()
.antMatchers("/test**").permitAll().antMatchers("/index.html").hasAnyRole("USER", "ADMIN")
.and()
'''
if test.html is your base file.
Related
When I launch my webapp I want spring to redirect to my login.jsp in order to authenticate before it goes to my home.jsp but when the app starts it immediately goes to my home.jsp. I created this SecurityFilterChain which I had thought would default to my login.jsp for authentication.
#Configuration
public class SecurityConfiguration {
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login", "/register").permitAll()
.and()
.formLogin()
.loginPage("/login").permitAll();
return http.build();
}
}
If more information is needed please let me know.
Edit
As pointed out by jzheaux down below. The naming convention of the method doesn’t matter. The fix was adding the .anyRequest().authenticated() which makes sure any other page besides the ones I had specified above it require authentication before you’re able to go to them.
I found what was wrong. I was using filterChain rather than the securityFilterChain. I also modified the method a little bit as shown here
#Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((requests) -> requests
.antMatchers("/login", "/register").permitAll()
.anyRequest().authenticated()
)
.formLogin((form) -> form
.loginPage("/login")
.loginProcessingUrl("/submit-login")
.permitAll()
)
.logout(LogoutConfigurer::permitAll);
return http.build();
}
Once making these changes the app defaulted to opening up my login.jsp for authentication before continuing on. Thank you all for the help.
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()
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/
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.
So I'm new to Spring, and learning in the way as I develop a web application using Spring-Boot.
Currently my page consists of two html pages: index.html and login.html. I'm also using Spring-Security.
Here's my current MvcConfig:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/login").setViewName("login");
}
}
The way the website is designed, an user goes to the url http://localhost:8080, then he/she is presented with the initial page, there's a login tab there where he/she can log in, and move to the dashboard view (which I will add later).
However, when I load the initial, the page is totally misconfigured (css / js / images resources aren't loaded). After I go to http://localhost:8080/login, perform the login and everything works again.
Therefore, any url of the form http://localhost:8080 is to be allowed (index.html), but anything else would require login.
Here's my Spring-Security config:
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.regexMatchers("/", "/index").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
How can I correctly configure my webpage?
*** Notes:
* I currently don't have any Controller class.
problem with regex matchers that i found is any resource loaded from your server you will need to account for in the mapping.
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login", "/admin").hasRole('ADMIN') // e.g. for pages that need to be authenticated
.anyRequest().permitAll() // all the others will be accessable by all
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
The most simplest way to do matching is following steps:
Declare your resource files by overriding addResourceHandlers
Use antmatchers to handle url security (simpler and easier), unless you have extremely dynamic urls with critical parameter
sorry guy, I will try to make it clear
anyRequest().authenticated() make your request to html resource need to authorized. You only permitAll to '/' & '/login'
so, add permitAll to css, js, image too
http
.authorizeRequests()
.regexMatchers("/", "/index").permitAll()
.antMatchers("/**/*.js", "/**/*.css").permitAll()
or more easy, make a style for login page. no depend on other static resource.