`
GodJohnny
  • 浏览: 92255 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

Spring Security实现自定义验证的两种方式及Restful登录验证

 
阅读更多
    在现实项目中,经常出现用户登录验证时,需要验证除了用户名、密码外的其他项,或额外的验证逻辑。当使用Spring Security框架时,就需要修改默认的验证方式。当以form表单方式登录时,可以有两种方式实现,任意实现一种即可。以Restful的方式提交JSON格式参数登录时或Restful,form方式混用时,可以两种方式结合使用。
    第一种方式,自定义AuthenticationProvider。这种方式在authenticate(Authentication authentication)方法中实现验证逻辑。supports方法返回true,才会执行authenticate方法。
实现完Provider后,需要在WebSecurityConfigurerAdapter中替换默认的AuthenticationProvider:
	@Autowired
	private MyAuthProvider authProvider;

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception   
        {
		auth.authenticationProvider(authProvider);
	}


    第二种方式,自定义AbstractAuthenticationProcessingFilter。这种方式通过覆写attemptAuthentication方法来实现验证逻辑。自定义Filter后,需要在WebSecurityConfigurerAdapter添加该Filter:
	@Bean
	public MyAuthFilter customUsernamePasswordAuthenticationFilter() throws Exception {
		MyAuthFilter customUsernamePasswordAuthenticationFilter = new MyAuthFilter();
		customUsernamePasswordAuthenticationFilter.setAuthenticationManager(authenticationManagerBean());
		customUsernamePasswordAuthenticationFilter
				.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login", "POST"));
		return customUsernamePasswordAuthenticationFilter;
	}
	// @formatter:off
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.addFilterBefore(customUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
		...
	}

 
     如果实际项目中,同时存在form登录和Restful方式的登录,可以两种方式结合使用或完全放在Filter中实现验证。在Filter中覆写obtainUsername、obtainPassword方法,解析JSON取得用户名、口令。然后再在Filter的attemptAuthentication方法或Provider中实现验证。

     参考资料:http://blog.csdn.net/xiejx618/article/details/42609497
               http://www.baeldung.com/spring-security-authentication-provider
               https://blog.codecentric.de/en/2012/07/spring-security-two-security-realms-in-one-application/
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics