900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > Spring boot 2.x+oauth2实现单点登录:基础准备之Spring Security

Spring boot 2.x+oauth2实现单点登录:基础准备之Spring Security

时间:2022-03-14 22:10:34

相关推荐

Spring boot 2.x+oauth2实现单点登录:基础准备之Spring Security

独角兽企业重金招聘Python工程师标准>>>

1.关于Spring Security

Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.

Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements

这是Spring Security的官方说明,大概是说Spring Security是一个功能强大且高度可定制的用于认证(authentication)和访问控制(access-control)的框架。该框架致力于为java应用提供认证(authentication)和授权(authorization),并且非常容易根据需要进行扩展,总之就是说Spring Security很diao啦。

2.在Spring boot中的基本使用

1)继承WebSecurityConfigurerAdapter,并重写configure(AuthenticationManagerBuilder auth) 和 configure(HttpSecurity http)方法。

@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate AuthUserService authUserService;@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(authUserService).passwordEncoder(new BCryptPasswordEncoder());}@Overrideprotected void configure(HttpSecurity http) throws Exception {//定义/login /upload不需要登录//定义登录页面为/loginhttp.authorizeRequests().antMatchers("/login","/register").permitAll().antMatchers("/css/**","/js/**").permitAll().anyRequest().authenticated().and().formLogin().loginPage("/login").successForwardUrl("/").permitAll().and().logout().permitAll();}}

@EnableWebSecurity和@Configuration注解表名了这是一个Spring Security配置类,有了这两个注解,Spring Security会自动去识别加载。

configure(HttpSecurity http)方法定义了哪些地方需要权限控制以及定义了自定义登录页(否则就会加载Spring Security的自带登录页)。

configure(AuthenticationManagerBuilder auth)方法定义了通过mybatis方式实现登录认证,以及规定了加密方法为:BCrypt。AuthenticationManagerBuilder用于创建一个AuthenticationManager,让我们能够轻松的实现内存验证、LADP验证、基于JDBC的验证、添加UserDetailsService、添加AuthenticationProvider

其中AuthUserService如下:

@Servicepublic class AuthUserService implements UserDetailsService {@Autowiredprivate UserService userService;@Overridepublic UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {var user=userService.login(s);if(user==null){throw new UsernameNotFoundException("User "+s+" not found.");}System.out.println(user.toString());List<SimpleGrantedAuthority> simpleGrantedAuthorities=new ArrayList<>();simpleGrantedAuthorities.add(new SimpleGrantedAuthority("USERADMIN"));return new User(user.getAccount(),user.getPassword(),simpleGrantedAuthorities);}}

UserService是调用mybatis方法获取user。

UserDetailsService是Spring Security内置的用户信息接口,实现此接口的loadUserByUsername方法后,和上面的SecurityConfig类结合起来,Spring Security会自动去验证账号密码,认证通过后就会跳转到预设的地址。

3.Spring Security认证原理

参考:Spring4all:Spring-Security-入门

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。