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

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

Related

Get another permission in permission - Spring security

I'm using Spring security for my project, and this is my configuration.
protected void configure(HttpSecurity http) throws Exception {
http.
authorizeRequests()
.antMatchers("/home").hasRole("USER")
.antMatchers("/edit-information/**").hasRole("USER")
.antMatchers("/admin/**").hasAnyRole("ADMIN_STAFF","ADMIN_MANAGER")
.antMatchers("/admin/employee").hasRole("ADMIN_MANAGER")
.and()
.formLogin()
.loginPage("/home/login")
.loginProcessingUrl("/j_spring_security_check")
.usernameParameter("email")
.passwordParameter("password")
.defaultSuccessUrl("/",true)
.failureUrl("/home/login-fail")
.and()
.exceptionHandling()
.accessDeniedPage("/403");
}
So it is my idea.
I want all ADMIN can log in to /admin/** but in /admin/** I have /admin/employee. I just want role ADMIN_MANAGER can log in here only.
But .antMatchers("/admin/**").hasAnyRole("ADMIN_STAFF","ADMIN_MANAGER") is already let ADMIN_STAFF log in to /admin/employee. I tried to add .antMatchers("/admin/employee").hasRole("ADMIN_MANAGER") but it did not work!
I do believe the problem is in the ordering for that antMatchers. The order of the rules matters and the more specific should come first, so instead of this:
.antMatchers("/admin/**").hasAnyRole("ADMIN_STAFF","ADMIN_MANAGER")
.antMatchers("/admin/employee").hasRole("ADMIN_MANAGER")
You can try this:
.antMatchers("/admin/employee").hasRole("ADMIN_MANAGER")
.antMatchers("/admin/**").hasAnyRole("ADMIN_STAFF","ADMIN_MANAGER")

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()

Spring security configuration; both Basic Auth and SiteMinder

I have a Spring boot web app that serves up both web content and exposes REST Services. The web content is protected by SiteMinder, the REST Services are protected by "Basic Auth".
I using Springs security 4.2.3. My Java code is extending the class WebSecurityConfigurerAdapter, my configure(HttpSecurity) method looks like:
#Override
protected void configure(HttpSecurity http) throws Exception {
RequestHeaderAuthenticationFilter siteMinderFilter = new RequestHeaderAuthenticationFilter();
siteMinderFilter.setAuthenticationManager(authenticationManager());
http
// Error page is for everyone
.authorizeRequests()
.antMatchers("/error.html")
.permitAll()
.anyRequest()
.anonymous()
// Basic Auth for our REST services
.and()
.authorizeRequests()
.antMatchers("/services/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint)
// Site-Minder protection for the web content
.and()
.addFilter(siteMinderFilter)
.authorizeRequests()
.antMatchers("/**").permitAll()
.anyRequest().hasRole(ApplicationConstants.SITE_MINDER_AUTHORITY);
http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
}
Is there something wrong with my configuration? Does my configuration create three separate filters? Maybe my question should be, how do I create the three filters?
When I attempt to call the REST Service using PostMan / "Basic Auth", I get the error message:
org.springframework.security.web.authentication.preauth.PreAuthenticatedCredentialsNotFoundException: SM_USER header not found in request.
I expect the service to get called, instead I get the SiteMinder filter firing.

Spring Security - configure HttpSecurity

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.

X-CSRF-TOKEN is not generated by Spring Boot

I followed the guide here: http://spring.io/guides/gs/rest-service/ to build my rest service example and now I am trying to enable the CSRF protection. I read that it should be enabled by default, so if I DON'T include:
http.csrf().disable()
in my WebSecurityConfigurerAdapter configuration, the CSRF protectection should be enabled by default, but it does not seem to to be the case. The problem is that the X-CSRF-TOKEN is not generated and not included in my HTTP response in any way.
What am I expected to do, to have the x-csrf-token generated and included in the response and, of course, the csrf protection fully working?
I noticed that, with a similar spring mvc configuration, I get the x-csrf-token generated simply including:
< security:csrf disabled="false"/>
in my security configuration file. But, with spring boot maybe I am getting something wrong and there is no way to have the csrf token generated. Can anybody help me, perhaps pointing me to a working example? My security configuration is:
#Override
protected void configure(HttpSecurity http) throws Exception
{
http
// .csrf().disable()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(new RestAuthenticationEntryPoint())
.and()
.formLogin()
.successHandler(new RestAuthenticationSuccessHandler())
.failureHandler(new SimpleUrlAuthenticationFailureHandler())
.and()
.logout()
.logoutSuccessHandler(new RestLogoutSuccessHandler());
}
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception
{
auth.userDetailsService(restUserDetailService);
}
To include the CSRF Token in your csrf protection, you can include CSRFTokenRepository to generate tokens. To illustrate in your case adding a simple line is enough:
#Override
protected void configure(HttpSecurity http) throws Exception
{
http.
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) //HERE ! Defaults XSRF-TOKEN as cookie name and X-XSRF-TOKEN as header name
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(new RestAuthenticationEntryPoint())
.and()
.formLogin()
.successHandler(new RestAuthenticationSuccessHandler())
.failureHandler(new SimpleUrlAuthenticationFailureHandler())
.and()
.logout()
.logoutSuccessHandler(new RestLogoutSuccessHandler());}
Using Spring security 5.3.0.Final, one of the ways you can generate the CSRF token is by setting it in the cookie using the following code below.
http.csrf(csrf -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()))
You also need to include the generated CSRF token in your request for the server to authorize.
<form>
<input type="hidden" name="_csrf" value="${cookie['XSRF-TOKEN'].getValue()}" />
//Code goes here
</form>
In the event you're using a JS framework, you need to include the token by setting it in the request header.
Here is an example for a JQuery ajax call.
// Get the CSRF token from the cookie
const csrfCookie= document.cookie.replace(/(?:(?:^|.*;\s*)XSRF-TOKEN\s*\=\s*([^;]*).*$)|^.*$/, '$1');
// Add the CSRF token to each ajax request header
settings.beforeSend = function(xhr) {
xhr.setRequestHeader('X-XSRF-TOKEN', springCsrfCookie);
};
$.ajax(settings);
There are other implementations that will suit your needs documented in the following link by Spring | https://docs.spring.io/spring-security/site/docs/5.3.0.RELEASE/reference/html5/#servlet-csrf
We had pretty similar issue during our security tests where we suspected that we accidentally disable csfr in configure method of websecurityconfig class,by default it is enabled. by changing the congfigure method as shown below , we had spring automatically generate csfr tokens.
websecurityconfig class configure method==>
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/login","/loginError","/home","/interruption").permitAll()
.antMatchers("/admin").hasAuthority(Roles.ROLE_PREFIX.role()+Roles.HALLEYYNT01.role())
.antMatchers("/requests").hasAuthority(Roles.ROLE_PREFIX.role()+Roles.CCHALLEYLOGIN.role())
.antMatchers("/solrequests").hasAuthority(Roles.ROLE_PREFIX.role()+Roles.SOLHALLEYLOGIN.role())
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
//.failureUrl("/loginError")
.loginProcessingUrl("/authenticate")
.defaultSuccessUrl("/")
.and()
.logout().clearAuthentication(true).invalidateHttpSession(true).deleteCookies("JSESSIONID")
.logoutSuccessUrl("/login");
//.and()
//.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
}

Categories

Resources