Authentication with Spring Security

1
Hello, I'm doing a project using the Spring Framework, and I need to do a very simple authentication, using users created in the same user table (without any integration with social networks). But I do not know how to do it, I'm using Spring and AngularJs , how do I get the user to authenticate? I have very little experience with Spring . Thank you.

    
asked by anonymous 29.08.2016 / 18:59

1 answer

3

Using JWT .

Manager:

public class CustomAuthenticationManager implements AuthenticationManager {

    @Autowired
    private UserRepository repository;



    @Override
    public Authentication authenticate(Authentication auth) throws AuthenticationException {
        try {
            User user = repository.findByEmail(auth.getName().toString());
            if (auth.getCredentials().toString().equals(user.getPassword())) {
                return auth;
            }
        } catch (NullPointerException e){
            throw new BadCredentialsException("Usuário não cadastrado!");
        }
        throw new BadCredentialsException("Senha incorreta");
    }
}

Configuration:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // disable caching
        http.headers().cacheControl();
        http.csrf().disable()
                // disable csrf for our requests.
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .cors()
                .and()
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers(HttpMethod.POST, "/login").permitAll()
                .antMatchers(HttpMethod.OPTIONS, "/login").permitAll()
                .antMatchers(HttpMethod.GET, "/api/questions/**").permitAll()
                .antMatchers(HttpMethod.GET, "/api/answers/**").permitAll()
                .antMatchers(HttpMethod.POST, "/api/users").permitAll()
                .antMatchers(HttpMethod.OPTIONS, "/api/users").permitAll()
                .antMatchers(HttpMethod.GET, "/api/comment/**").permitAll()
                .anyRequest().authenticated()
                .and()
                // We filter the api/login requests
                .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class)
                // And filter other requests to check the presence of JWT in header
                .addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowCredentials(true);
        configuration.addAllowedOrigin("*"); //Cors
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        configuration.addExposedHeader("Authorization");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return new CustomAuthenticationManager();
    }
}

Service to authenticate the token:

public class TokenAuthenticationService {

    private long EXPIRATIONTIME = 1000 * 60 * 60 * 24 * 10; // 10 days
    private String secret = "Meu secret";
    private String tokenPrefix = "Bearer";
    private String headerString = "Authorization";
    public void addAuthentication(HttpServletResponse response, String username)
    {
        // We generate a token now.
        String JWT = Jwts.builder()
                    .setSubject(username)
                    .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
                    .signWith(SignatureAlgorithm.HS512, secret)
                    .compact();
        response.addHeader(headerString,tokenPrefix + " "+ JWT);
    }

    public String getUserName(String token){
        if(token != null)
        {
            // parse the token.
            String username = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody()
                    .getSubject();
            if(username != null) // we managed to retrieve a user
            {
                return username;
            }
        }
        return null;
    }

    public Authentication getAuthentication(HttpServletRequest request)
    {
        String token = request.getHeader(headerString);
        if(token != null)
        {
            // parse the token.
            String username = Jwts.parser()
                        .setSigningKey(secret)
                        .parseClaimsJws(token)
                        .getBody()
                        .getSubject();
            if(username != null) // we managed to retrieve a user
            {
                return new AuthenticatedUser(username);
            }
        }
        return null;
    }
}
    
11.11.2016 / 13:38