For multiple purposes I need to use
SecurityContextHolder.getContext().getAuthentication()
methods in my controllers/services.
I did migrate my app to Spring Boot 1.4.1 from XML configured Spring MVC app (now only Java configs), similar approach worked before.
I have a problem calling SecurityContextHolder.getContext().getAuthentication(), for example in this controller:
#RestController
#Secured("IS_AUTHENTICATED_ANONYMOUSLY")
#RequestMapping("utils")
public class UtilsController {
#RequestMapping(value = "/check_auth", method = RequestMethod.GET)
public Boolean getAuthState() throws SQLException {
if (SecurityContextHolder.getContext().getAuthentication() == null){
logger.info("Auth obj null");
}
if (SecurityContextHolder.getContext().getAuthentication().getName() != null && SecurityContextHolder.getContext().getAuthentication().getName() != "anonymousUser") {
return true;
} else return false;
}
}
it always returns null. Can't figure out why anonymous authentication is not working.
Here is the Spring Security configuration:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).and()
.formLogin()
.successHandler(ajaxSuccessHandler)
.failureHandler(ajaxFailureHandler)
.loginProcessingUrl("/authentication")
.passwordParameter("password")
.usernameParameter("username")
.and()
.logout()
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.and()
.csrf().disable()
// .anonymous().disable()
.authorizeRequests()
// .anyRequest().anonymous()
.antMatchers("/utils").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/admin/*").access("hasRole('ROLE_ADMIN')")
.antMatchers("/user/*").access("hasRole('ROLE_USER')");
}
I did tried with and without #Secured annotation on the controller.
.authorizeRequests()
// .anyRequest().anonymous()
.antMatchers("/utils").permitAll()
different variations with this settings.
You are getting null with:
SecurityContextHolder.getContext().getAuthentication()
because you are not authenticating within you security configuration.
You can add a simple:
.authenticated()
.and()
// ...
.formLogin();
in case you're using form login.
Now after you'll authenticate each request you suppose to get something other than null.
Here's an example from Spring Security docs:
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**", "/signup", "/about").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.anyRequest().authenticated()
.and()
// ...
.formLogin();
}
Related
I am using spring security in my java project to secure web services.
All my web services are secured here are filter chain configuiration that i use:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and()
.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilter(new JwtEmailAndPasswordAuthenticationFilter(authenticationManager(), jwtConfig, secretKey))
.addFilterAfter(new JwtTokenVerifier(secretKey, jwtConfig),JwtEmailAndPasswordAuthenticationFilter.class)
.authorizeRequests()
.anyRequest()
.authenticated();
}
Now I have a requirement to create one web service that will be accessible to everybody.
For this purpose I add this row:
.and().authorizeRequests().antMatchers("/auth/reset").permitAll()
To chained filers and it looks like that:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and()
.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilter(new JwtEmailAndPasswordAuthenticationFilter(authenticationManager(), jwtConfig, secretKey))
.addFilterAfter(new JwtTokenVerifier(secretKey, jwtConfig),JwtEmailAndPasswordAuthenticationFilter.class)
.authorizeRequests()
.and().authorizeRequests().antMatchers("/auth/reset").permitAll()
.anyRequest()
.authenticated();
}
After adding the row above I get exception JWT not found, it comes from this JwtTokenVerifier bean which is fired by
addFilterAfter.
My question is how can I prevent trigger addFilterAfter or any other filter that is needed only for the secured routes in case of the request for an unsecured web service?
UPDATE
Here is definition of JwtTokenVerifier bean:
public class JwtTokenVerifier extends OncePerRequestFilter {
private final SecretKey secretKey;
private final JwtConfig jwtConfig;
public JwtTokenVerifier(SecretKey secretKey,
JwtConfig jwtConfig) {
this.secretKey = secretKey;
this.jwtConfig = jwtConfig;
}
#Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
try {
String authorizationHeader = request.getHeader(jwtConfig.getAuthorizationHeader());
if (Strings.isNullOrEmpty(authorizationHeader) || !authorizationHeader.startsWith(jwtConfig.getTokenPrefix())) {
filterChain.doFilter(request, response);
return;
}
String token = authorizationHeader.replace(jwtConfig.getTokenPrefix(), "");
try {
Jws<Claims> claimsJws = Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token);
Claims body = claimsJws.getBody();
String email = body.getSubject();
var authorities = (List<Map<String, String>>) body.get("authorities");
Set<SimpleGrantedAuthority> simpleGrantedAuthorities = authorities.stream()
.map(m -> new SimpleGrantedAuthority(m.get("authority")))
.collect(Collectors.toSet());
Authentication authentication = new UsernamePasswordAuthenticationToken(
email,
null,
simpleGrantedAuthorities
);
SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (JwtException e) {
throw new IllegalStateException(String.format("Token %s cannot be trusted", token));
}
filterChain.doFilter(request, response);
} catch (JwtException e) {
throw e;
}
}
}
I realize you didn't ask this, but I'd first recommend that you use Spring Security's built-in JWT support instead of building your own. Security is hard, and using vetted support is likely more secure.
Regarding your question about having separate auth mechanisms for separate endpoints, you can instead publish two filter chains, one for open endpoints and one for token-based endpoints like so:
#Bean
#Order(0)
SecurityFilterChain open(HttpSecurity http) {
http
.requestMatchers((requests) -> requests.antMatchers("/auth/reset"))
.authorizeHttpRequests((authorize) -> authorize.anyRequest().permitAll());
return http.build();
}
#Bean
SecurityFilterChain tokenBased(HttpSecurity http) {
http
.authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated())
.addFilter(...)
.addFilterAfter(...);
return http.build();
}
Have you tried something like that :
.and()
.authorizeRequests()
.antMatchers("...").permitAll()
.and()
.addFilter(...)
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
I have the following security config file :
#Configuration
#EnableWebSecurity
public class EvaluariSecurityConfig extends WebSecurityConfigurerAdapter {
// add a reference to our security data source
#Autowired
private DataSource securityDataSource;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// use jdbc authentication ... oh yeah!!!
auth.jdbcAuthentication().dataSource(securityDataSource);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/evaluator/**").hasRole("EVALUATOR")
.antMatchers("/**").permitAll()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/authenticateTheUser")
.successHandler(new SavedRequestAwareAuthenticationSuccessHandler())
.permitAll()
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/")
.and()
.csrf().ignoringAntMatchers("/authenticateTheUser")
.and()
.csrf()
.disable()
.cors();
}
}
My problem is that the login works fine when running locally but when I host the app on AWS Elastic Beanstalk, it sometimes responds with the 302 http code. It's important to say that this is not happening all the time but it's quite annoying when it does. At the moment the app is not working over https yet (it's http).
Any ideas why this is happening ?
For a project that has no spring security. All controllers (GET/POST) of the project are not secured and should stay unsecured. But now, I have a new Controller and i want to secure its path (/private), sub-pathes and parameters. Only this one path must be secured with Basic Authentication. Why is my code not working?
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").permitAll()
.antMatchers("/private**").hasAuthority("ADMIN").and().httpBasic();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password("{noop}pass")
.roles("ADMIN");
}
}
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/private").hasRole("ADMIN")
.antMatchers("/private/**").hasRole("ADMIN")
.antMatchers("/**").permitAll()
.and()
.httpBasic();
or
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/private").hasRole("ADMIN")
.antMatchers("/private/**").hasRole("ADMIN")
.anyRequest().permitAll()
.and()
.httpBasic();
I have a problem with Spring Security authentication failure handler redirect with parameter.
In security config when I use
failureUrl("/login.html?error=true")
it works. But when I use custom authentication failure handler (as shown below), it always returns: url/login.html
getRedirectStrategy().sendRedirect(request, response, "/login.html?error=true");
or
response.sendRedirect(request.getContextPath() + "/login.html?error=true");
I don't know whats wrong. Why does it not show the parameter ?error=true?
Info: I am using Spring + JSF + Hibernate + Spring Security
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html")
.usernameParameter("j_username")
.passwordParameter("j_password")
.loginProcessingUrl("/j_spring_security_check")
.failureHandler(customAuthenticationFailureHandler)// .failureUrl("/login.html?error=true")//.successHandler(authSuccsessHandler)
.defaultSuccessUrl("/dashboard.html")
.permitAll()
.and()
.logout()
.invalidateHttpSession(true)
.logoutSuccessUrl("/")
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/access.html")
.and()
.headers()
.defaultsDisabled()
.frameOptions()
.sameOrigin()
.cacheControl();
http
.csrf().disable();
}
This is custom authentication failure handler:
#Component
public class CustomAuthFailureHandler extends SimpleUrlAuthenticationFailureHandler {
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
getRedirectStrategy().sendRedirect(request, response, "/login.html?error=true");
}
}
I will change parameter for some cases.
You didn't allow anonymous access to URL /login.html?error=true, so you are redirected to the login page (/login.html).
AbstractAuthenticationFilterConfigurer#permitAll allows access (for anyone) to failure URL but not for custom failure handler:
Ensures the urls for failureUrl(String) as well as for the HttpSecurityBuilder, the getLoginPage() and getLoginProcessingUrl() are granted access to any user.
You have to allow access explicitly with AbstractRequestMatcherRegistry#antMatchers:
Maps a List of AntPathRequestMatcher instances that do not care which HttpMethod is used.
and ExpressionUrlAuthorizationConfigurer.AuthorizedUrl#permitAll:
Specify that URLs are allowed by anyone.
You don't have to allow the exact URL /login.html?error=true, because AntPathRequestMatcher ignores the query string:
Matcher which compares a pre-defined ant-style pattern against the URL ( servletPath + pathInfo) of an HttpServletRequest. The query string of the URL is ignored and matching is case-insensitive or case-sensitive depending on the arguments passed into the constructor.
Your modified configuration:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login.html").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html")
.usernameParameter("j_username")
.passwordParameter("j_password")
.loginProcessingUrl("/j_spring_security_check")
.failureHandler(customAuthenticationFailureHandler)// .failureUrl("/login.html?error=true")//.successHandler(authSuccsessHandler)
.defaultSuccessUrl("/dashboard.html")
.permitAll()
.and()
.logout()
.invalidateHttpSession(true)
.logoutSuccessUrl("/")
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/access.html")
.and()
.headers()
.defaultsDisabled()
.frameOptions()
.sameOrigin()
.cacheControl();
http
.csrf().disable();
}
In the case of OAuth token failure, I am getting below response, which is inconsistent with app response style.
{
"error": "invalid_token",
"error_description": "Invalid access token: 4cbc6f1c-4d47-44bd-89bc-92a8c86d88dbsdfsdfs"
}
I just wanted to use common response object for the consistency.
Following approach worked for me.
Build your resource server with your custom entry-point object
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.authenticationEntryPoint(new CustomOAuth2AuthenticationEntryPoint());
}
and here is your custom entry point
public class CustomOAuth2AuthenticationEntryPoint extends OAuth2AuthenticationEntryPoint{
public CustomOAuth2AuthenticationEntryPoint() {
super.setExceptionTranslator(new CustomOAuth2WebResponseExceptionTranslator());
}
}
here is your custom WebResponseExceptionTranslator, In my case I have just used a replica of DefaultWebResponseExceptionTranslator and rewritten handleOAuth2Exception method.
CustomOAuth2WebResponseExceptionTranslator implements WebResponseExceptionTranslator<Response> {
....
.....
private ResponseEntity<Response> handleOAuth2Exception(OAuth2Exception e) throws IOException {
int status = e.getHttpErrorCode();
HttpHeaders headers = new HttpHeaders();
headers.set("Cache-Control", "no-store");
headers.set("Pragma", "no-cache");
if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) {
headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
}
ResponseEntity<Response> response =new ResponseEntity<>(new Response().message(e.getMessage()).status(StatusEnum.ERROR)
.errorType(e.getClass().getName()), HttpStatus.UNAUTHORIZED);
return response;
}
Result looks like
{
"status": "error",
"message": "Invalid access token: 4cbc6f1c-4d47-44bd-89bc-92a8c86d88dbsdfsdfs",
"error_type": "org.springframework.security.oauth2.common.exceptions.InvalidTokenException"
}
I have the following config method for my WebSecurityConfig that extends WebSecurityConfigurerAdapter:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.and()
.authorizeRequests()
.antMatchers("/signup").permitAll()
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.addFilterBefore(
new JWTAuthenticationFilter(userDetailsServiceBean()),
UsernamePasswordAuthenticationFilter.class);
}
JWTAuthenticationFilter actually filters requests received on all endpoints, and checks if they have the correct JWT authentication token in their headers.
I don't expect this filter to execute on requests made to the /login endpoint ! Is there a way to ignore the filter for special endpoints ? (here /login and /signup).
Is there any good reason to keep this filter executing on requests made to all endpoints including login and signup ?
You can try adding the following
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/login**", "/signup**");
}