官术网_书友最值得收藏!

Setting up AuthenticationManager

There are number of built-in AuthenticationManager in Spring Security that can be easily used in your application. Spring Security also has a number of helper classes, using which you can set up AuthenticationManager. One helper class is AuthenticationManagerBuilder. Using this class, its quite easy to set up UserDetailsService against a database, in memory, in LDAP, and so on. If the need arises, you could also have your own custom UserDetailsService (maybe a custom single sign-on solution is already there in your organization).

You can make an AuthenticationManager global, so it will be accessible by your entire application. It will be available for method security and other WebSecurityConfigurerAdapter instances. WebSecurityConfigurerAdapter is a class that is extended by your Spring configuration file, making it quite easy to bring Spring Security into your Spring application. This is how you set up a global AuthenticationManager using the @Autowired annotation:

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
public void confGlobalAuthManager(AuthenticationManagerBuilder auth) throws
Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("admin@password").roles("ROLE_ADMIN");
}
}

You can also create local AuthenticationManager, which is only available for this particular WebSecurityConfigurerAdapterby overriding the configure method, as shown in the following code:

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("admin@password").roles("ROLE_ADMIN");
}
}

Another option is to expose the AuthenticationManager bean by overriding authenticationManagerBean method, as shown here:

@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}

You can also expose various AuthenticationManager, AuthenticationProvider, or UserDetailsService as beans which will override the default ones.

In the preceding code examples we have used AuthenticationManagerBuilder to configure in-memory authentication. More mechanisms of the AuthenticationManagerBuilder class will be used in the subsequent examples in this chapter.

主站蜘蛛池模板: 阜阳市| 海南省| 胶州市| 乌兰察布市| 巨鹿县| 株洲县| 玉田县| 衡东县| 元氏县| 巫溪县| 辽源市| 天镇县| 威海市| 文成县| 图木舒克市| 襄城县| 盈江县| 蓝田县| 丰原市| 鄂托克前旗| 界首市| 云和县| 徐汇区| 南和县| 河曲县| 上杭县| 北海市| 鄱阳县| 广德县| 砚山县| 巴楚县| 伊吾县| 乐都县| 衡水市| 宁乡县| 铜陵市| 老河口市| 七台河市| 昌黎县| 荣昌县| 望奎县|