详解spring security 配置多个AuthenticationProvider

姓名: 李小娜

[嵌牛导读]:这篇文章主要介绍了详解spring security 配置多个AuthenticationProvider

[嵌牛鼻子]:spring security的大体介绍   开始配置多AuthenticationProvider  

[嵌牛提问] :spring security 如何配置多个AuthenticationProvider?

[嵌牛正文] :spring security的大体介绍

spring security本身如果只是说配置,还是很简单易懂的(我也不知道网上说spring

security难,难在哪里),简单不需要特别的功能,一个WebSecurityConfigurerAdapter的实现,然后实现UserServiceDetails就是简单的数据库验证了,这个我就不说了。

spring security大体上是由一堆Filter(所以才能在spring

mvc前拦截请求)实现的,Filter有几个,登出Filter(LogoutFilter),用户名密码验证Filter(UsernamePasswordAuthenticationFilter)之类的,Filter再交由其他组件完成细分的功能,例如最常用的UsernamePasswordAuthenticationFilter会持有一个AuthenticationManager引用,AuthenticationManager顾名思义,验证管理器,负责验证的,但AuthenticationManager本身并不做具体的验证工作,AuthenticationManager持有一个AuthenticationProvider集合,AuthenticationProvider才是做验证工作的组件,AuthenticationManager和AuthenticationProvider的工作机制可以大概看一下这两个的java

doc,然后成功失败都有相对应该Handler 。大体的spring security的验证工作流程就是这样了。

开始配置多AuthenticationProvider

首先,写一个内存认证的AuthenticationProvider,这里我简单地写一个只有root帐号的AuthenticationProvider


packagecom.scau.equipment.config.common.security.provider;

importorg.springframework.security.authentication.AuthenticationProvider;

importorg.springframework.security.authentication.UsernamePasswordAuthenticationToken;

importorg.springframework.security.core.Authentication;

importorg.springframework.security.core.AuthenticationException;

importorg.springframework.security.core.GrantedAuthority;

importorg.springframework.security.core.authority.SimpleGrantedAuthority;

importorg.springframework.security.core.userdetails.User;

importorg.springframework.stereotype.Component;

importjava.util.Arrays;

importjava.util.List;

/**

* Created by Administrator on 2017-05-10.

*/

@Component

publicclassInMemoryAuthenticationProviderimplementsAuthenticationProvider {

privatefinalString adminName ="root";

privatefinalString adminPassword ="root";

//根用户拥有全部的权限

privatefinalList authorities = Arrays.asList(newSimpleGrantedAuthority("CAN_SEARCH"),

newSimpleGrantedAuthority("CAN_SEARCH"),

newSimpleGrantedAuthority("CAN_EXPORT"),

newSimpleGrantedAuthority("CAN_IMPORT"),

newSimpleGrantedAuthority("CAN_BORROW"),

newSimpleGrantedAuthority("CAN_RETURN"),

newSimpleGrantedAuthority("CAN_REPAIR"),

newSimpleGrantedAuthority("CAN_DISCARD"),

newSimpleGrantedAuthority("CAN_EMPOWERMENT"),

newSimpleGrantedAuthority("CAN_BREED"));

@Override

publicAuthentication authenticate(Authentication authentication)throwsAuthenticationException {

if(isMatch(authentication)){

User user =newUser(authentication.getName(),authentication.getCredentials().toString(),authorities);

returnnewUsernamePasswordAuthenticationToken(user,authentication.getCredentials(),authorities);

}

returnnull;

}

@Override

publicbooleansupports(Class authentication) {

returntrue;

}

privatebooleanisMatch(Authentication authentication){

if(authentication.getName().equals(adminName)&&authentication.getCredentials().equals(adminPassword))

returntrue;

else

returnfalse;

}

}

support方法检查authentication的类型是不是这个AuthenticationProvider支持的,这里我简单地返回true,就是所有都支持,这里所说的authentication为什么会有多个类型,是因为多个AuthenticationProvider可以返回不同的Authentication。

public Authentication authenticate(Authentication authentication) throws

AuthenticationException 方法就是验证过程。

如果AuthenticationProvider返回了null,AuthenticationManager会交给下一个支持authentication类型的AuthenticationProvider处理。

另外需要一个数据库认证的AuthenticationProvider,我们可以直接用spring

security提供的DaoAuthenticationProvider,设置一下UserServiceDetails和PasswordEncoder就可以了


@Bean

DaoAuthenticationProvider daoAuthenticationProvider(){

DaoAuthenticationProvider daoAuthenticationProvider =newDaoAuthenticationProvider();

daoAuthenticationProvider.setPasswordEncoder(newBCryptPasswordEncoder());

daoAuthenticationProvider.setUserDetailsService(userServiceDetails);

returndaoAuthenticationProvider;

}

最后在WebSecurityConfigurerAdapter里配置一个含有以上两个AuthenticationProvider的AuthenticationManager,依然重用spring

security提供的ProviderManager




packagecom.scau.equipment.config.common.security;

importcom.scau.equipment.config.common.security.handler.AjaxLoginFailureHandler;

importcom.scau.equipment.config.common.security.handler.AjaxLoginSuccessHandler;

importcom.scau.equipment.config.common.security.provider.InMemoryAuthenticationProvider;

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.context.annotation.Bean;

importorg.springframework.context.annotation.Configuration;

importorg.springframework.security.authentication.AuthenticationManager;

importorg.springframework.security.authentication.ProviderManager;

importorg.springframework.security.authentication.dao.DaoAuthenticationProvider;

importorg.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;

importorg.springframework.security.config.annotation.authentication.configurers.provisioning.InMemoryUserDetailsManagerConfigurer;

importorg.springframework.security.config.annotation.authentication.configurers.provisioning.UserDetailsManagerConfigurer;

importorg.springframework.security.config.annotation.web.builders.HttpSecurity;

importorg.springframework.security.config.annotation.web.builders.WebSecurity;

importorg.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

importorg.springframework.security.core.GrantedAuthority;

importorg.springframework.security.core.authority.SimpleGrantedAuthority;

importorg.springframework.security.core.userdetails.UserDetailsService;

importorg.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

importjava.util.Arrays;

importjava.util.List;

/**

* Created by Administrator on 2017/2/17.

*/

@Configuration

publicclassSecurityConfigextendsWebSecurityConfigurerAdapter {

@Autowired

UserDetailsService userServiceDetails;

@Autowired

InMemoryAuthenticationProvider inMemoryAuthenticationProvider;

@Bean

DaoAuthenticationProvider daoAuthenticationProvider(){

DaoAuthenticationProvider daoAuthenticationProvider =newDaoAuthenticationProvider();

daoAuthenticationProvider.setPasswordEncoder(newBCryptPasswordEncoder());

daoAuthenticationProvider.setUserDetailsService(userServiceDetails);

returndaoAuthenticationProvider;

}

@Override

protectedvoidconfigure(HttpSecurity http)throwsException {

http

.csrf().disable()

.rememberMe().alwaysRemember(true).tokenValiditySeconds(86400).and()

.authorizeRequests()

.antMatchers("/","/*swagger*/**","/v2/api-docs").permitAll()

.anyRequest().authenticated().and()

.formLogin()

.loginPage("/")

.loginProcessingUrl("/login")

.successHandler(newAjaxLoginSuccessHandler())

.failureHandler(newAjaxLoginFailureHandler()).and()

.logout().logoutUrl("/logout").logoutSuccessUrl("/");

}

@Override

publicvoidconfigure(WebSecurity web)throwsException {

web.ignoring().antMatchers("/public/**","/webjars/**","/v2/**","/swagger**");

}

@Override

protectedAuthenticationManager authenticationManager()throwsException {

ProviderManager authenticationManager =newProviderManager(Arrays.asList(inMemoryAuthenticationProvider,daoAuthenticationProvider()));

//不擦除认证密码,擦除会导致TokenBasedRememberMeServices因为找不到Credentials再调用UserDetailsService而抛出UsernameNotFoundException

authenticationManager.setEraseCredentialsAfterAuthentication(false);

returnauthenticationManager;

}

/**

* 这里需要提供UserDetailsService的原因是RememberMeServices需要用到

*@return

*/

@Override

protectedUserDetailsService userDetailsService() {

returnuserServiceDetails;

}

}

基本上都是重用了原有的类,很多都是默认使用的,只不过为了修改下行为而重新配置。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容