RESTfulWebサービスを使用するSpringBootアプリケーションで、SpringSocialおよびと一緒にSpringSecurityを構成しましたSpringSocialConfigurer
。
現在、認証/承認には2つの方法があります。ユーザー名/パスワードを使用する方法と、Twitterなどのソーシャルネットワークを使用する方法です。
Spring MVC RESTコントローラーで独自のRESTfulエンドポイントを介して認証/承認を実装するために、次のメソッドを追加しました。
@RequestMapping(value = "/login", method = RequestMethod.POST)
public Authentication login(@RequestBody LoginUserRequest userRequest) {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userRequest.getUsername(), userRequest.getPassword()));
boolean isAuthenticated = isAuthenticated(authentication);
if (isAuthenticated) {
SecurityContextHolder.getContext().setAuthentication(authentication);
}
return authentication;
}
private boolean isAuthenticated(Authentication authentication) {
return authentication != null && !(authentication instanceof AnonymousAuthenticationToken) && authentication.isAuthenticated();
}
しかし、/login
エンドポイントの呼び出しが成功した後、正確に何をクライアントに返す必要があるのかわかりません。完全な認証オブジェクトを返すことは冗長だと思います。
認証が成功した場合、クライアントに何を返す必要がありますか?
このログイン方法を正しく実装する方法を教えてください。
また、RESTfullログインのUsernamePasswordAuthenticationToken
場合は、Twitter経由のログインの場合はSocialAuthenticationToken
、同じアプリケーションに異なるトークンを入れても大丈夫ですか?
のメソッドをオーバーライドすることで、認証が成功したときに何を返すかを構成できます。 SimpleUrlAuthenticationSuccessHandler
public class CustomAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
public CustomAuthenticationSuccessHandler() {
super();
setRedirectStrategy(new NoRedirectStrategy());
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
super.onAuthenticationSuccess(request, response, authentication);
ObjectMapper mapper = new ObjectMapper();
response.setContentType("application/json;charset=UTF-8");
response.getWriter().print(mapper.writeValueAsString(objectToBereturned);
response.getWriter().flush();
}
protected class NoRedirectStrategy implements RedirectStrategy {
@Override
public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url)
throws IOException {
// any redirect if required. leave the implementation black if not needed
}
}
}
さらに、障害応答を処理することもできます。
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加