1

私は春のセキュリティの新機能です。私はauthenticationを実行する私のspring-bootアプリケーションにJWTを実装しようとしています。私はコード例を続けて、jwtを生成することができました。しかし、サンプルファイルで行われた設定の通り、HttpRequestの入力を、設定のインメモリデータセットで検証することができます。しかし、私はusernamepasswordrequestに送付して、私のdatabaseにある値で確認する方法を理解していません。私を案内してください。マイコンフィギュレーションクラスは春のブートと春のセキュリティを備えたJWT

@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http.csrf().disable().authorizeRequests() 
      .antMatchers("/").permitAll() 
      .antMatchers(HttpMethod.POST, "/login").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); 
} 

@Override 
protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
    // Create a default account 
    auth.inMemoryAuthentication() 
      .withUser("admin") 
      .password("password") 
      .roles("ADMIN"); 
} 
} 

ここでオーバーライドconfigure(AuthenticationManagerBuilder auth) throws Exceptionで、私はあなたがUserDetailsS​​erviceを実装する必要が/loginパス

public class TokenAuthenticationService { 

static final long EXPIRATIONTIME = 864_000_000; // 10 days 
static final String SECRET = "ThisIsASecret"; 
static final String TOKEN_PREFIX = "Bearer"; 
static final String HEADER_STRING = "Authorization"; 

static void addAuthentication(HttpServletResponse res, String username)  { 
    String JWT = Jwts.builder() 
      .setSubject(username) 
      .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME)) 
      .signWith(SignatureAlgorithm.HS512, SECRET) 
      .compact(); 
    res.addHeader(HEADER_STRING, TOKEN_PREFIX + " " + JWT); 
} 

static Authentication getAuthentication(HttpServletRequest request) { 
    String token = request.getHeader(HEADER_STRING); 
    if (token != null) { 
     // parse the token. 
     String user = Jwts.parser() 
       .setSigningKey(SECRET) 
       .parseClaimsJws(token.replace(TOKEN_PREFIX, "")) 
       .getBody() 
       .getSubject(); 

     return user != null ? 
       new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList()) : 
       null; 
    } 
    return null; 
} 
} 

public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter { 

public JWTLoginFilter(String url, AuthenticationManager authManager) { 
super(new AntPathRequestMatcher(url)); 
setAuthenticationManager(authManager); 
} 

@Override 
public Authentication attemptAuthentication(
     HttpServletRequest req, HttpServletResponse res) 
     throws AuthenticationException, IOException, ServletException { 
    AccountCredentials creds = new ObjectMapper() 
      .readValue(req.getInputStream(), AccountCredentials.class); 
    return getAuthenticationManager().authenticate(
      new UsernamePasswordAuthenticationToken(
        creds.getUsername(), 
        creds.getPassword(), 
        Collections.emptyList() 
      ) 
    ); 
} 

@Override 
protected void successfulAuthentication(
     HttpServletRequest req, 
     HttpServletResponse res, FilterChain chain, 
     Authentication auth) throws IOException, ServletException { 
    TokenAuthenticationService 
      .addAuthentication(res, auth.getName()); 
} 
} 

public class JWTAuthenticationFilter extends GenericFilterBean{ 

@Override 
public void doFilter(ServletRequest request, 
        ServletResponse response, 
        FilterChain filterChain) 
     throws IOException, ServletException { 
    Authentication authentication = TokenAuthenticationService 
      .getAuthentication((HttpServletRequest)request); 

    SecurityContextHolder.getContext() 
      .setAuthentication(authentication); 
    filterChain.doFilter(request,response); 
} 
} 

答えて

1

ためrequestに存在する資格情報と比較される資格情報を設定することができていますインターフェイス(データベースへのアクセス)を設定し、Spring Securityで使用するように設定します。

いい例(ここではJWTはありませんが、これは意味がありません):Spring Security: Authentication with a Database-backed UserDetailsService

関連する問題