SHARE
TWEET

Untitled

a guest Oct 17th, 2017 125 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. antMatchers("/api/v1/signup").permitAll().
  2.    
  3. message=An Authentication object was not found in the SecurityContext, type=org.springframework.security.authentication.AuthenticationCredentialsNotFoundException
  4.    
  5. @Override
  6.     protected void configure(HttpSecurity http) throws Exception {
  7.  
  8.          http.
  9.          csrf().disable().
  10.          sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
  11.          and().
  12.          authorizeRequests().
  13.          antMatchers("/api/v1/signup").permitAll().
  14.          anyRequest().authenticated().
  15.          and().
  16.          anonymous().disable();
  17.         http.addFilterBefore(new AuthenticationFilter(authenticationManager()), BasicAuthenticationFilter.class);
  18.     }
  19.    
  20. @Override
  21.     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  22.         HttpServletRequest httpRequest = asHttp(request);
  23.         HttpServletResponse httpResponse = asHttp(response);
  24.  
  25.         String username = httpRequest.getHeader("X-Auth-Username");
  26.         String password = httpRequest.getHeader("X-Auth-Password");
  27.         String token = httpRequest.getHeader("X-Auth-Token");
  28.  
  29.         String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest);
  30.  
  31.         try {
  32.  
  33.             if (postToAuthenticate(httpRequest, resourcePath)) {            
  34.                 processUsernamePasswordAuthentication(httpResponse, username, password);
  35.                 return;
  36.             }
  37.  
  38.             if(token != null){
  39.                 processTokenAuthentication(token);
  40.             }
  41.             chain.doFilter(request, response);
  42.         } catch (InternalAuthenticationServiceException internalAuthenticationServiceException) {
  43.             SecurityContextHolder.clearContext();
  44.             logger.error("Internal authentication service exception", internalAuthenticationServiceException);
  45.             httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
  46.         } catch (AuthenticationException authenticationException) {
  47.             SecurityContextHolder.clearContext();
  48.             httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage());
  49.         } finally {
  50.         }
  51.     }
  52.  
  53.      private HttpServletRequest asHttp(ServletRequest request) {
  54.             return (HttpServletRequest) request;
  55.         }
  56.  
  57.         private HttpServletResponse asHttp(ServletResponse response) {
  58.             return (HttpServletResponse) response;
  59.         }
  60.  
  61.         private boolean postToAuthenticate(HttpServletRequest httpRequest, String resourcePath) {
  62.             return Constant.AUTHENTICATE_URL.equalsIgnoreCase(resourcePath) && httpRequest.getMethod().equals("POST");
  63.         }
  64.  
  65.         private void processUsernamePasswordAuthentication(HttpServletResponse httpResponse,String username, String password) throws IOException {
  66.             Authentication resultOfAuthentication = tryToAuthenticateWithUsernameAndPassword(username, password);
  67.             SecurityContextHolder.getContext().setAuthentication(resultOfAuthentication);
  68.             httpResponse.setStatus(HttpServletResponse.SC_OK);
  69.             httpResponse.addHeader("Content-Type", "application/json");
  70.             httpResponse.addHeader("X-Auth-Token", resultOfAuthentication.getDetails().toString());
  71.         }
  72.  
  73.         private Authentication tryToAuthenticateWithUsernameAndPassword(String username,String password) {
  74.             UsernamePasswordAuthenticationToken requestAuthentication = new UsernamePasswordAuthenticationToken(username, password);
  75.             return tryToAuthenticate(requestAuthentication);
  76.         }
  77.  
  78.         private void processTokenAuthentication(String token) {
  79.             Authentication resultOfAuthentication = tryToAuthenticateWithToken(token);
  80.             SecurityContextHolder.getContext().setAuthentication(resultOfAuthentication);
  81.         }
  82.  
  83.         private Authentication tryToAuthenticateWithToken(String token) {
  84.             PreAuthenticatedAuthenticationToken requestAuthentication = new PreAuthenticatedAuthenticationToken(token, null);
  85.             return tryToAuthenticate(requestAuthentication);
  86.         }
  87.  
  88.         private Authentication tryToAuthenticate(Authentication requestAuthentication) {
  89.             Authentication responseAuthentication = authenticationManager.authenticate(requestAuthentication);
  90.             if (responseAuthentication == null || !responseAuthentication.isAuthenticated()) {
  91.                 throw new InternalAuthenticationServiceException("Unable to authenticate Domain User for provided credentials");
  92.             }
  93.             logger.debug("User successfully authenticated");
  94.             return responseAuthentication;
  95.         }
  96.    
  97. @RestController
  98. public class UserController {
  99.  
  100.     @Autowired
  101.     UserService userService;
  102.  
  103.     /**
  104.      * to pass user info to service
  105.      */
  106.     @RequestMapping(value = "api/v1/signup",method = RequestMethod.POST)
  107.     public String saveUser(@RequestBody User user) {
  108.         userService.saveUser(user);
  109.         return "User registerted successfully";
  110.     }
  111. }
  112.    
  113. @Override
  114. public void configure(WebSecurity web) throws Exception {
  115.     web.ignoring().antMatchers("/api/v1/signup");
  116. }
  117.    
  118. <http pattern="/resources/**" security="none"/>
  119.    
  120. web.ignoring().antMatchers("/resources/**");
  121.    
  122. <intercept-url pattern="/resources/**" filters="none"/>
  123.    
  124. <intercept-url pattern="/login*" filters="none" />
  125.    
  126. @EnableWebSecurity
  127. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  128.  
  129.     @Override
  130.     protected void configure(HttpSecurity http) throws Exception {
  131.         http.authorizeRequests()
  132.                 .antMatchers("/web/admin/**").hasAnyRole(ADMIN.toString(), GUEST.toString())
  133.                 .anyRequest().permitAll()
  134.                 .and()
  135.                 .formLogin().loginPage("/web/login").permitAll()
  136.                 .and()
  137.                 .csrf().ignoringAntMatchers("/contact-email")
  138.                 .and()
  139.                 .logout().logoutUrl("/web/logout").logoutSuccessUrl("/web/").permitAll();
  140.     }
  141.  
  142.     @Autowired
  143.     public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
  144.         auth.inMemoryAuthentication()
  145.                 .withUser("admin").password("admin").roles(ADMIN.toString())
  146.                 .and()
  147.                 .withUser("guest").password("guest").roles(GUEST.toString());
  148.     }
  149.  
  150. }
  151.    
  152. .csrf().ignoringAntMatchers("/contact-email")
  153.    
  154. http
  155.     .authorizeRequests()
  156.     .antMatchers("/api/v1/signup/**").permitAll()
  157.     .anyRequest().authenticated()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top