Advertisement
Guest User

Untitled

a guest
Jan 20th, 2019
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.57 KB | None | 0 0
  1.  
  2. //LoginFilter.java
  3. public class LoginFilter extends AbstractAuthenticationProcessingFilter {
  4.     public LoginFilter(String url, AuthenticationManager authenticationManager) {
  5.         super(new AntPathRequestMatcher(url));
  6.         setAuthenticationManager(authenticationManager);
  7.     }
  8.     @Override
  9.     public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException, IOException, ServletException {
  10.         AccountCredentials cred = new ObjectMapper().readValue(req.getInputStream(), AccountCredentials.class);
  11.        
  12.         return getAuthenticationManager().authenticate(
  13.                 new UsernamePasswordAuthenticationToken(cred.getUsername(), cred.getPassword(), Collections.emptyList()));
  14.     }
  15.  
  16.     @Override
  17.     protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
  18.         AuthenticationService.addToken(response, authResult.getName());
  19.     }
  20. }
  21. //SecurityConfig.java
  22. @Override
  23.     protected void configure(HttpSecurity http) throws Exception {
  24.         http.cors().and().authorizeRequests()
  25.                 .antMatchers(HttpMethod.POST, "/login").permitAll()
  26.                 .anyRequest().authenticated()
  27.                 .and()
  28.                 .addFilterBefore(new LoginFilter("/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class)
  29.                 .addFilterBefore(new AuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
  30.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement