(接上篇)

后台


先说一下AuthConfig.java Spring Security的主要配置文件之一 AuthConfig

 1 @Configuration
2 @EnableWebSecurity
3 public class AuthConfig extends WebSecurityConfigurerAdapter {
4 @Override
5 protected void configure(HttpSecurity httpSecurity) throws Exception {
6 httpSecurity.authorizeRequests()
7 .antMatchers("/css/**","/staic/**", "/js/**","/images/**").permitAll()
8 .antMatchers("/", "/login","/session_expired").permitAll()
9 .and()
10 .formLogin()
11 .loginPage("/login")
12 .defaultSuccessUrl("/main_menu")
13 .failureUrl("/loginError")
14 .usernameParameter("txtUserCd")
15 .passwordParameter("txtUserPwd")
16 .permitAll()
17 .and()
18 .logout()
19 .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
20 .logoutSuccessUrl("/")
21 .deleteCookies("JSESSIONID")
22 .invalidateHttpSession(true)
23 .permitAll()
24 .and()
25 .sessionManagement()
26 .invalidSessionUrl("/session_expired")
27 .maximumSessions(1)
28 .maxSessionsPreventsLogin(true)
29 .expiredUrl("/session_expired");
30 httpSecurity.logout().permitAll();
31
32 }
33
34 @Autowired
35 AuthUserService authUserService;
36 public void globalAuthConfig(AuthenticationManagerBuilder auth) throws Exception {
37 auth.userDetailsService(authUserService);
38 //auth.inMemoryAuthentication().withUser("user").password("password");
39 }
40 /*@Configuration
41 protected static class AuthenticationConfiguration extends GlobalAuthenticationConfigurerAdapter {
42 @Autowired
43 AuthUserService authUserService;
44
45 @Override
46 public void init(AuthenticationManagerBuilder auth) throws Exception {
47 //auth.inMemoryAuthentication().withUser("user").password("password");
48 auth.userDetailsService(authUserService);
49 }
50 }*/
51 }

一、configur方法 基本配置

No Source Comment
L1 @Configuration 这个就是java形式的bean spring3.0以后 允许以 @Configuration 注解来代替XML形式的bean
L2 @EnableWebSecurity 用这个注解开启 spring security配置验证开启
L3 WebSecurityConfigurerAdapter 这个需要我们继承WebSecurityConfigurerAdapter适配器且重写

configure 函数 来实现访问的控制(那些访问/资源 需要哪些权限)和登录的验证(数据库验证/内存验证)

L6 authorizeRequests() 通过authorizeRequests()配下的子函来完成访问/授权 配置
L7,8 antMatchers/permitAll antMatchers里配置的资源是可以被所有用户访问(permitAll)的
L9 and() 类似于结束标签
L10 formLogin 通过formLogin()配下的函数对登录form进行配置
L11 loginPage 设置登录页面
L12 defaultSuccessUrl 默认登录成功跳转地址
L13 failureUrl 默认登录失败跳转地址
L14,15 usernameParameter
passwordParameter
用户名密码验证用 *这里的参数要和画面上控件名保持一致
L18  logout() 通过logout()配下的函数对注销进行配置
L19 .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) 设置注销用的请求URL
L20 logoutSuccessUrl 设置注销成功后的跳转URL
L21 deleteCookies 消除Cookie
L22 invalidateHttpSession 销毁Session
L25 sessionManagement 通过sessionManagement配下的函数对session配置
L27 maximumSessions 同一用户session上限设定 *比如同一个用户 多次登录
L28 maxSessionsPreventsLogin maximumSessions设定的上限启用 * 超出报错
L29 expiredUrl

超过session上限跳转URL设定

二、globalAuthConfig方法 认证

先说L38 这行注掉的 是内存认证模式  意思是创建了一个 名为user 密码 为password的用户

然后是 L37 这也是认证核心

先看一下这个 传入参数的的构成 也就是 AuthUserService 类

 1 @Service
2 public class AuthUserService implements UserDetailsService{
3
4 @Autowired
5 MstUsersMapper mstUsersMapper;
6
7 @Override
8 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
9 Users users =mstUsersMapper.selectByPrimaryKey(username);
10 if(users == null) {
11 throw new UsernameNotFoundException("User not found for name:"+username);
12 }
13 return new AuthUser(users);
14 }
15
16 public String getAuthorityByLoginId(String loginId ){
17 //Map<String,String> authKindMap = new HashMap<String,String>();
18 String auth = mstUsersMapper.selectAuthorityByLoginId(loginId);
19 return auth;
20 }
21 }

可以看到我们是 实现了UserDetailsService 然后重写了一个loadUserByUsername和追加了一个 getAuthorityByLoginId函数

关于 getAuthorityByLoginId 好说的基本上就是 当前用户的权限

然后是loadUserByUsername

可以通过名字基本上可以看的出是 通过name 取user 的信息 实际上也是这样 这里并不判断你输的密码对不对 主要是

判断你输入的用户名在数据库里存不存在 不存在 报错 扔出 存在 实例化一个 AuthUser 返回

这个AuthUser 类也很重要 实现了UserDetails  如下

 1 public class AuthUser implements UserDetails {
2 private static final long serialVersionUID = 1L;
3
4 private String userId;
5 private String loginId;
6 private String password;
7 private String authorityKind;
8 public AuthUser(Users users) {
9 super();
10 this.userId = users.getUserId();
11 this.loginId = users.getLoginId();
12 this.password = users.getPassword();
13 this.authorityKind = users.getAuthorityKind();
14 }
15
16 @Override
17 public Collection<GrantedAuthority> getAuthorities() {
18 List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
19 list.add(new SimpleGrantedAuthority(authorityKind));
20 return list;
21 }
22
23 @Override
24 public String getPassword() {
25 return password;
26 }
27
28 @Override
29 public String getUsername() {
30 return loginId;
31 }
32
33 @Override
34 public boolean isAccountNonExpired() {
35 return true;
36 }
37
38 @Override
39 public boolean isAccountNonLocked() {
40 return true;
41 }
42
43 @Override
44 public boolean isCredentialsNonExpired() {
45 return true;
46 }
47
48 @Override
49 public boolean isEnabled() {
50 return true;
51 }

这里的几个点要注意一下

L17 getAuthorities 它返回了一个权限集合 这个集合是和你在画面侧用的hasAnyAuthority('ROLE_USER','ROLE_ADMIN') 这个函数相呼应的

换言之你之所以能在画面侧如上那样写也是因为你在这里吧把当前用户的权限set进去了

然后看一下我们实现的 UserDetails这个父类,如下官网文档给的信息.

No Modifier and Type Method and Description
1 java.util.Collection<? extends GrantedAuthority> getAuthorities()

Returns the authorities granted to the user.
2 java.lang.String getPassword()

Returns the password used to authenticate the user.
3 java.lang.String getUsername()

Returns the username used to authenticate the user.
4 boolean isAccountNonExpired()

Indicates whether the user's account has expired.
5 boolean isAccountNonLocked()

Indicates whether the user is locked or unlocked.
6 boolean isCredentialsNonExpired()

Indicates whether the user's credentials (password) has expired.
7 boolean isEnabled()

Indicates whether the user is enabled or disabled.

前3个应该不用说了,从第四个开始说一下

isAccountNonExpired():当前账号是否已经过期

isAccountNonLocked():当前账号是否被锁

isCredentialsNonExpired():当前账号证书(密码)是否过期

isEnabled():当前账号是否被禁用

都要给设成true 否则登录会报出来

还有实现一个UserDetailsService类如下

 @Service
public class AuthUserService implements UserDetailsService{ @Autowired
MstUsersMapper mstUsersMapper; @Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Users users =mstUsersMapper.selectByPrimaryKey(username);
if(users == null) {
throw new UsernameNotFoundException("User not found for name:"+username);
}
return new AuthUser(users);
} public String getAuthorityByLoginId(String loginId ){
//Map<String,String> authKindMap = new HashMap<String,String>();
String auth = mstUsersMapper.selectAuthorityByLoginId(loginId);
return auth;
}
}
如你看到那样loadUserByUsername这函数并不做密码验证只是拿username取用户信息,当然取不到报错
取到交给AuthUser,然后spring boot 自己再去判断密码,以及前面说的那个几个check
剩下的就是 Controller这个就没有特别要说的到git上看代码就完了
最后贴一下执行效果图及git地址

(完)

spring boot系列03--spring security (基于数据库)登录和权限控制(下)的更多相关文章

  1. spring boot系列--spring security (基于数据库)登录和权限控制

    先说一下AuthConfig.java Spring Security的主要配置文件之一 AuthConfig 1 @Configuration 2 @EnableWebSecurity 3 publ ...

  2. spring boot系列03--spring security (基于数据库)登录和权限控制(上)

    这篇打算写一下登陆权限验证相关 说起来也都是泪,之前涉及权限的比较少所以这次准备起来就比较困难. 踩了好几个大坑,还好最终都一一消化掉(这是废话你没解决你写个什么劲

  3. 【spring boot 系列】spring data jpa 全面解析(实践 + 源码分析)

    前言 本文将从示例.原理.应用3个方面介绍spring data jpa. 以下分析基于spring boot 2.0 + spring 5.0.4版本源码 概述 JPA是什么? JPA (Java ...

  4. Spring Boot系列(一) Spring Boot准备知识

    本文是学习 Spring Boot 的一些准备知识. Spring Web MVC Spring Web MVC 的两个Context 如下图所示, 基于 Servlet 的 Spring Web M ...

  5. Spring Boot系列(四) Spring Cloud 之 Config Client

    Config 是通过 PropertySource 提供. 这节的内容主要是探讨配置, 特别是 PropertySource 的加载机制. Spring Cloud 技术体系 分布式配置 服务注册/发 ...

  6. Spring Boot系列(四) Spring Boot 之验证

    这节没有高深的东西, 但有一些学习思路值得借鉴. JSR 303 (Bean Validation) Maven依赖 <dependency> <groupId>org.spr ...

  7. Spring Boot系列(三) Spring Boot 之 JDBC

    数据源 类型 javax.sql.DataSource javax.sql.XADataSource org.springframework.jdbc.datasource.embedded,Enbe ...

  8. Spring Boot系列二 Spring @Async异步线程池用法总结

    1. TaskExecutor Spring异步线程池的接口类,其实质是java.util.concurrent.Executor Spring 已经实现的异常线程池: 1. SimpleAsyncT ...

  9. Spring Security实现统一登录与权限控制

    1  项目介绍 最开始是一个单体应用,所有功能模块都写在一个项目里,后来觉得项目越来越大,于是决定把一些功能拆分出去,形成一个一个独立的微服务,于是就有个问题了,登录.退出.权限控制这些东西怎么办呢? ...

随机推荐

  1. 近期对FTP及Excel数据处理的一些摸索

    一个多月没写随笔了,主要是发的东西,自己感觉也很垃圾,说又说回来,谁不是从垃圾变强的,所以不比比,还得努力.come on!! Python学习也有段时间了,近期为了解决同事的一个难题,所以我们决定联 ...

  2. XML文档读取-DOM

    DOM(Document Object Model),“文档对象模型”早期是为了解决不用浏览器间数据兼容问题提出的解决方案,现在已经是W3C组织推荐的处理可扩展标志语言的标准编程接口. W3C DOM ...

  3. scrapy爬虫框架setting模块解析

    平时写爬虫的时候并不需要设置setting里所有的参数,今天心血来潮,花了点时间查了一下setting模块创建后自动写入的所有参数的含义,记录一下. 模块相关说明信息 # -*- coding: ut ...

  4. 源生js惯性滚动与回弹效果

    在写移动端的APP或者页面时,经常会遇到惯性滚动与回弹效果.用插件iscroll可以轻松解决这个问题,大多数的移动框架也能轻松解决这个问题,它们内部都封装了这个效果. 一直好奇这个效果原生JS是怎么实 ...

  5. 工作随笔——selenium支持post请求,支持自定义header

    背景: 最近在写一个小程序,发现博主所在的地区访问该网站时有防ddos功能验证导致程序不能正常工作. 经过试验发现可以用国外代理ip解决这个问题,但是程序走代理访问延迟高且不稳定. 思路: selen ...

  6. iOS10 相册权限

    当我升级到Xcode8后,启动我的相机项目,直接crash,输出的日志如下: '2016-07-08 16:41:11.268943 project-name[362:56625] [MC] Syst ...

  7. iOS 类似2048、4096小游戏-OC

    大概思路(初步制作,粗工制造):demo 1.Collection 创建cell 2.cell上添加一个view,用来添加手势 3.字典用来存放数据->每次执行StarGame数组接收没有数字的 ...

  8. hibernate 3.6.10 maven pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...

  9. C语言_第二讲_规范以及常用数据类型

    一丶编码规范基本数据类型 编码规范 任何程序员,都应该有良好的的编码习惯,便于以后的代码可读性和维护 常见了编码规范有 匈牙利命名法 驼峰式大小写 匈牙利命名法: 是电脑程序设计中的一种变量命名规则, ...

  10. Java SE 8 流库(三)

    1.7. Optional类型 容器对象,可能包含或不包含非空值.如果存在一个值,isPresent()将返回true,get()将返回值.还提供了依赖于包含值是否存在的附加方法,如orElse()( ...