Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Autowired
- private JwtAuthenticationEntryPoint unauthorizedHandler;
- @Autowired
- private UserDetailsService userDetailsService;
- @Autowired
- public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
- authenticationManagerBuilder
- .userDetailsService(this.userDetailsService)
- .passwordEncoder(passwordEncoder());
- }
- @Bean
- public PasswordEncoder passwordEncoder() {
- return new BCryptPasswordEncoder();
- }
- @Bean
- public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
- return new JwtAuthenticationTokenFilter();
- }
- @Bean
- @Override
- public AuthenticationManager authenticationManagerBean() throws Exception {
- // TODO Auto-generated method stub
- return super.authenticationManagerBean();
- }
- @Override
- protected void configure(HttpSecurity httpSecurity) throws Exception {
- httpSecurity
- // we don't need CSRF because our token is invulnerable
- .csrf().disable()
- .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
- // don't create session
- .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
- .authorizeRequests()
- //.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
- // allow anonymous resource requests
- .antMatchers(
- HttpMethod.GET,
- "/",
- "/*.html",
- "/favicon.ico",
- "/**/*.html",
- "/**/*.css",
- "/**/*.js"
- ).permitAll()
- .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
- .antMatchers("/auth/**").permitAll()
- .anyRequest().authenticated();
- // Custom JWT based security filter
- httpSecurity
- .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
- // disable page caching
- httpSecurity.headers().cacheControl();
- }
- @Mapper
- public interface UserMapper {
- User findByUsername(String username);
- }
- @Autowired
- private UserDetailsService userDetailsService;
- @Autowired
- private JwtTokenUtil jwtTokenUtil;
- @Value("${jwt.header}")
- private String tokenHeader;
- @Override
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
- HttpServletRequest httpRequest = (HttpServletRequest) request;
- String authToken = httpRequest.getHeader(this.tokenHeader);
- // authToken.startsWith("Bearer ")
- // String authToken = header.substring(7);
- String username = jwtTokenUtil.getUsernameFromToken(authToken);
- if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
- UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
- if (jwtTokenUtil.validateToken(authToken, userDetails)) {
- UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
- authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
- SecurityContextHolder.getContext().setAuthentication(authentication);
- }
- }
- chain.doFilter(request, response);
- }
- @RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST)
- public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest, Device device) throws AuthenticationException {
- // Perform the security
- final Authentication authentication = authenticationManager.authenticate(
- new UsernamePasswordAuthenticationToken(
- System.out.println("Username: " + authenticationRequest.getUsername() + " / password: " + authenticationRequest.getPassword());
- authenticationRequest.getUsername(),
- authenticationRequest.getPassword()
- )
- );
- SecurityContextHolder.getContext().setAuthentication(authentication);
- // Reload password post-security so we can generate token
- final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
- final String token = jwtTokenUtil.generateToken(userDetails, device);
- // Return the token
- return ResponseEntity.ok(new JwtAuthenticationResponse(token));
- }
- @Service
- public class JwtUserDetailsServiceImpl implements UserDetailsService {
- @Autowired
- private UserMapper userMapper;
- @Override
- public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
- System.out.println("Username in ServiceImpl: " + username);
- User user = userMapper.findByUsername(username);
- if (user == null) {
- throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
- } else {
- return JwtUserFactory.create(user);
- }
- }
- server:
- contextPath:
- spring:
- jackson:
- serialization:
- INDENT_OUTPUT: true
- datasource:
- master:
- driver-class-name: "com.mysql.jdbc.Driver"
- url: "jdbc:mysql://localhost:3306/test"
- user-name: "test"
- password: "testtest"
- jwt:
- header: Authorization
- secret: mySecret
- expiration: 604800
- route:
- authentication:
- path: auth
- refresh: refresh
- logging:
- level:
- org.springframework:
- security: DEBUG
- <mapper namespace="xxxxxx">
- <select id="findByUsername" parameterType="String"
- resultType="xxxxxx">
- <![CDATA[
- SELECT * FROM user WHERE username = #{username}
- ]]>
- </select>
- </mapper>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement