Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @EnableWebSecurity
- @EnableJpaRepositories(basePackageClasses = AccountRepo.class)
- @Configuration
- @EnableGlobalMethodSecurity(securedEnabled=true, prePostEnabled=true)
- public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
- @Autowired
- private UserDetailsService userDetailsService;
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
- }
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .cors()
- .and()
- .csrf().disable()
- // add filters
- .addFilter(new JWTAuthenticationFilter(authenticationManager()))
- .addFilter(new JWTAuthorizationFilter(authenticationManager()))
- // don't create session
- .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
- .authorizeRequests()
- .antMatchers(authenticationUrl).permitAll()
- .anyRequest().authenticated()
- .and()
- .csrf().disable();
- }
- @Bean(name="passwordEncoder")
- public PasswordEncoder passwordEncoder() {
- return new BCryptPasswordEncoder();
- }
- @Bean
- CorsConfigurationSource corsConfigurationSource() {
- final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
- source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
- return source;
- }
- }
- public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
- private AuthenticationManager authenticationManager;
- public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
- this.authenticationManager = authenticationManager;
- }
- @Override
- public Authentication attemptAuthentication(HttpServletRequest req,
- HttpServletResponse res) throws AuthenticationException {
- try {
- AuthenticationRequest creds = new ObjectMapper()
- .readValue(req.getInputStream(), AuthenticationRequest.class);
- return authenticationManager.authenticate(
- new UsernamePasswordAuthenticationToken(
- creds.getEmail(),
- creds.getPassword(),
- new ArrayList<>())
- );
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- @Override
- protected void successfulAuthentication(HttpServletRequest req,
- HttpServletResponse res,
- FilterChain chain,
- Authentication auth) throws IOException, ServletException {
- String token = Jwts.builder()
- .setSubject(((User) auth.getPrincipal()).getUsername())
- .setExpiration(Date.from(OffsetDateTime.now().plusMinutes(EXPIRATION_TIME).toInstant()))
- .signWith(SignatureAlgorithm.HS512, SECRET.getBytes())
- .compact();
- res.addHeader(HEADER_STRING, TOKEN_PREFIX + token);
- }
- }
- @Service
- public class UserDetailsServiceImpl implements UserDetailsService {
- @Autowired
- private AccountService service;
- @Override
- public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
- VAccount account = service.getAccountByEmail(email);
- if(account == null) {
- throw new UsernameNotFoundException("no user found with email '" + email + "'");
- }
- Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
- for (VRole role : account.getRoles()){
- System.out.println(role.getName().toString());
- grantedAuthorities.add(new SimpleGrantedAuthority(role.getName().toString()));
- }
- return new org.springframework.security.core.userdetails.User(account.getEmail(), account.getPassHash(), grantedAuthorities);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement