我必须说我对整个模型非常困惑,我需要帮助将所有漂浮的部分粘在一起。
我不是在做Spring REST,只是简单的WebMVC控制器。
我的使命: 我想要一个带有用户名+通过身份验证的表单登录。我想对第三方服务进行身份验证。成功后我想返回一个cookie但不使用默认的cookie令牌机制。我想让cookie改为使用JWT令牌。通过利用cookie机制,每个请求都将与JWT一起发送。
所以为了分解它,我有以下模块来处理:
成功验证后,使用我的自定义实现替换cookie会话令牌
每次请求都从cookie中解析JWT(使用过滤器)
从JWT中提取用户详细信息/数据,以便控制器可以访问
令人困惑的是什么? (请在我错的地方纠正我)
第三方身份验证
要对第三方进行身份验证,我需要通过扩展AuthenticationProvider
来拥有自定义提供程序public class JWTTokenAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate( Authentication authentication ) throws AuthenticationException {
// auth against 3rd party
// return Authentication
return new UsernamePasswordAuthenticationToken( name, password, new ArrayList<>() );
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals( UsernamePasswordAuthenticationToken.class );
}
}
问题:
用JWT替换Cookie令牌
不知道如何优雅地做到这一点,我可以想到多种方式,但他们不是Spring Security的方式,我不想打破这种流程。非常感谢这里的任何建议!
根据Cookie的每个请求解析JWT
根据我的理解,我需要像这样扩展AbstractAuthenticationProcessingFilter
public class CookieAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
@Override
public Authentication attemptAuthentication( HttpServletRequest request, HttpServletResponse response )
throws AuthenticationException, IOException, ServletException {
String token = "";
// get token from a Cookie
// create an instance to Authentication
TokenAuthentication authentication = new TokenAuthentication(null, null);
return getAuthenticationManager().authenticate(tokenAuthentication);
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
super.doFilter(req, res, chain);
}
}
问题:
似乎我拥有了我需要的所有部分,除了更换cookie会话,但是我不能把它们放到一个连贯的模型中,我需要一个能够很好地理解这些机制的人,所以我可以将所有这些都粘合到一起单个模块。
更新1
此过滤器将自身注册到POST - &gt; &#34; /登录&#34;然后创建UsernamePasswordAuthenticationToken的实例并将控件传递给下一个过滤器。
问题是设置cookie会话的地方....
更新2
dos的这一部分给出了我失踪的顶级流程,无论是谁通过这个看看这里...... http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#tech-intro-authentication
有关AuthenticationProvider的此部分... http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#core-services-authentication-manager
更新3 - 工作案例,这是最好的方法吗?
因此,在深入了解Spring Security文档及其来源后,我得到了初始模型。现在,这样做,我意识到有不止一种方法可以做到这一点。任何关于为什么采取这种方式的建议VS丹尼斯在下面提出的建议?
下面的工作示例......
答案 0 :(得分:10)
为了让这个按照原始帖子中描述的方式工作,这就是需要发生的事情......
自定义过滤器
public class CookieAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public CookieAuthenticationFilter( RequestMatcher requestMatcher ) {
super( requestMatcher );
setAuthenticationManager( super.getAuthenticationManager() );
}
@Override
public Authentication attemptAuthentication( HttpServletRequest request, HttpServletResponse response )
throws AuthenticationException, IOException, ServletException {
String token = "";
// get token from a Cookie
Cookie[] cookies = request.getCookies();
if( cookies == null || cookies.length < 1 ) {
throw new AuthenticationServiceException( "Invalid Token" );
}
Cookie sessionCookie = null;
for( Cookie cookie : cookies ) {
if( ( "someSessionId" ).equals( cookie.getName() ) ) {
sessionCookie = cookie;
break;
}
}
// TODO: move the cookie validation into a private method
if( sessionCookie == null || StringUtils.isEmpty( sessionCookie.getValue() ) ) {
throw new AuthenticationServiceException( "Invalid Token" );
}
JWTAuthenticationToken jwtAuthentication = new JWTAuthenticationToken( sessionCookie.getValue(), null, null );
return jwtAuthentication;
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
super.doFilter(req, res, chain);
}
}
身份验证提供程序
将提供程序附加到由UsernamePasswordAuthenticationFilter生成的UsernamePasswordAuthenticationToken,后者将自身附加到“/ login”POST。对于带有POST到“/ login”的formlogin,将生成UsernamePasswordAuthenticationToken,并且将触发您的提供者
@Component
public class ApiAuthenticationProvider implements AuthenticationProvider {
@Autowired
TokenAuthenticationService tokenAuthService;
@Override
public Authentication authenticate( Authentication authentication ) throws AuthenticationException {
String login = authentication.getName();
String password = authentication.getCredentials().toString();
// perform API call to auth against a 3rd party
// get User data
User user = new User();
// create a JWT token
String jwtToken = "some-token-123"
return new JWTAuthenticationToken( jwtToken, user, new ArrayList<>() );
}
@Override
public boolean supports( Class<?> authentication ) {
return authentication.equals( UsernamePasswordAuthenticationToken.class );
}
}
自定义身份验证对象
对于JWT,我们希望拥有自己的身份验证令牌对象来携带我们想要的数据。
public class JWTAuthenticationToken extends AbstractAuthenticationToken {
User principal;
String token;
public JWTAuthenticationToken( String token, User principal, Collection<? extends GrantedAuthority> authorities ) {
super( authorities );
this.token = token;
this.principal = principal;
}
@Override
public Object getCredentials() {
return null;
}
@Override
public Object getPrincipal() {
return principal;
}
public void setToken( String token ) {
this.token = token;
}
public String getToken() {
return token;
}
}
身份验证成功处理程序
当我们的自定义提供程序通过向第三方验证用户并生成JWT令牌来执行此操作时,这将被调用。这是Cookie进入响应的位置。
@Component
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(
HttpServletRequest request,
HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
if( !(authentication instanceof JWTAuthenticationToken) ) {
return;
}
JWTAuthenticationToken jwtAuthenticaton = (JWTAuthenticationToken) authentication;
// Add a session cookie
Cookie sessionCookie = new Cookie( "someSessionId", jwtAuthenticaton.getToken() );
response.addCookie( sessionCookie );
//clearAuthenticationAttributes(request);
// call the original impl
super.onAuthenticationSuccess( request, response, authentication );
}
}
将这一切联系在一起
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired @Required
ApiAuthenticationProvider apiAuthProvider;
@Autowired @Required
AuthenticationSuccessHandler authSuccessHandler;
@Autowired @Required
SimpleUrlAuthenticationFailureHandler authFailureHandler;
@Override
protected void configure( AuthenticationManagerBuilder auth ) throws Exception {
auth.authenticationProvider( apiAuthProvider );
}
@Override
protected void configure( HttpSecurity httpSecurity ) throws Exception {
httpSecurity
// don't create session
.sessionManagement()
.sessionCreationPolicy( SessionCreationPolicy.STATELESS )
.and()
.authorizeRequests()
.antMatchers( "/", "/login", "/register" ).permitAll()
.antMatchers( "/js/**", "/css/**", "/img/**" ).permitAll()
.anyRequest().authenticated()
.and()
// login
.formLogin()
.failureHandler( authFailureHandler )
//.failureUrl( "/login" )
.loginPage("/login")
.successHandler( authSuccessHandler )
.and()
// JWT cookie filter
.addFilterAfter( getCookieAuthenticationFilter(
new AndRequestMatcher( new AntPathRequestMatcher( "/account" ) )
) , UsernamePasswordAuthenticationFilter.class );
}
@Bean
SimpleUrlAuthenticationFailureHandler getAuthFailureHandler() {
SimpleUrlAuthenticationFailureHandler handler = new SimpleUrlAuthenticationFailureHandler( "/login" );
handler.setDefaultFailureUrl( "/login" );
//handler.setUseForward( true );
return handler;
}
CookieAuthenticationFilter getCookieAuthenticationFilter( RequestMatcher requestMatcher ) {
CookieAuthenticationFilter filter = new CookieAuthenticationFilter( requestMatcher );
filter.setAuthenticationFailureHandler( authFailureHandler );
return filter;
}
}
答案 1 :(得分:0)
最简单的方法是将Spring Session添加到项目中并扩展HttpSessionStrategy,为会话创建/销毁事件提供方便的钩子,并具有从HttpServletRequest中提取会话的方法。