私は最近、スプリングブートアプリケーションでJWT認証をSpringセキュリティで実装しました。 /login
の要求が来たら、JWTAuthenticationFilter
が実行されます。JWTの役割ベースの認証
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
{
UserModel creds = new ObjectMapper().readValue(req.getInputStream(), UserModel.class);
return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(creds.getMobileNumber(),
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(new Date(System.currentTimeMillis() + 360000000))
.signWith(SignatureAlgorithm.HS512, SecurityConstants.SECRET).compact();
res.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX + token);
res.setStatus(HttpServletResponse.SC_OK);
String tokenJsonResponse = new ObjectMapper().writeValueAsString("Ok");
res.addHeader("Content-Type", "application/json");
res.getWriter().print(tokenJsonResponse);
}
}
送信する前にJWTにロールを追加したいと思います。 JWTでの役割の追加方法 私がコードから理解できるのは、ログイン要求が来たときに、userName
とpassword
が含まれています。ObjectMapper
は、それが指定されたクラスの1つにマッピングされています。では、データベースからそのユーザーの役割をどのように抽出できますか?
getAuthorities()はどのようにデータベースからロールをフェッチしますか? –
あなたは、新しいArrayList <>()を追加しました。あなたはあなたが新しいArrayList <>()を追加しました。権限のリストの代わりに空の権限リストのように振る舞うでしょう。ユーザーの役割を得て、空の配列リストの代わりに最後のargとしてUsernamePasswordAuthenticationTokenを渡すべきです。 –
私が理解しているところから、 'attemptAuthentication()'を入力します。ユーザーが認証される前にその方法でデータベースからロールデータを取得するように指示していますか? –