手机快速登录 spring security权限控制
- 第9章 移动端开发-手机快速登录、权限控制
- 1. 需求分析
- 2.1 页面调整
- 2.1.1 发送验证码
- 加密小知识
- 3. 权限控制
- 3.1 认证和授权概念
- 3.2 权限模块数据模型
- 3.3 Spring Security简介
- 3.4实现
第9章 移动端开发-手机快速登录、权限控制
1. 需求分析
手机快速登录功能,就是通过短信验证码的方式进行登录。这种方式相对于用户名密码登录方式,用户
不需要记忆自己的密码,只需要通过输入手机号并获取验证码就可以完成登录,是目前比较流行的登录
方式。
2.1 页面调整
登录页面为/pages/login.html
2.1.1 发送验证码
为获取验证码按钮绑定事件,并在事件对应的处理函数中校验手机号,如果手机号输入正确则显示30秒
倒计时效果并发送ajax请求,发送短信验证码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0,user-scalable=no,minimal-ui">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../img/asset-favico.ico">
<title>登录</title>
<link rel="stylesheet" href="../css/page-health-login.css" />
<link rel="stylesheet" href="../plugins/elementui/index.css" />
<script src="../plugins/jquery/dist/jquery.min.js"></script>
<script src="../plugins/healthmobile.js"></script>
<script src="../plugins/vue/vue.js"></script>
<script src="../plugins/vue/axios-0.18.0.js"></script>
<script src="../plugins/elementui/index.js"></script>
</head>
<body data-spy="scroll" data-target="#myNavbar" data-offset="150">
<div class="app" id="app">
<!-- 页面头部 -->
<div class="top-header">
<span class="f-left"><i class="icon-back"></i></span>
<span class="center">传智健康</span>
<span class="f-right"><i class="icon-more"></i></span>
</div>
<div style="margin-left: 20px">手机快速登录</div>
<!-- 页面内容 -->
<div class="contentBox">
<div class="login">
<form id='login-form'>
<div class="input-row">
<label>手机号</label>
<div class="loginInput">
<input v-model="loginInfo.telephone" id='account' type="text" placeholder="请输入手机号">
<input id="validateCodeButton" @click="sendValidateCode()" type="button" style="font-size: 12px" value="获取验证码">
</div>
</div>
<div class="input-row">
<label>验证码</label>
<div class="loginInput">
<input v-model="loginInfo.validateCode" style="width:80%" id='password' type="text" placeholder="请输入验证码">
</div>
</div>
<div class="input-row" style="font-size: 12px">
<input type="checkbox" checked>
阅读并同意《传智健康用户协议》《传智健康隐私条款》
</div>
<div class="btn yes-btn"><a @click="login()" href="#">登录</a></div>
</form>
</div>
</div>
</div>
</body>
<script>
var vue = new Vue({
el:'#app',
data:{
loginInfo:{}//登录信息
},
methods:{
//发送验证码
sendValidateCode(){
var telephone = this.loginInfo.telephone;
if (!checkTelephone(telephone)) {
this.$message.error('请输入正确的手机号');
return false;
}
validateCodeButton = $("#validateCodeButton")[0];
clock = window.setInterval(doLoop, 1000); //一秒执行一次
axios.post("/validateCode/send4Login.do?telephone=" + telephone).then((response) => {
if(!response.data.flag){
//验证码发送失败
this.$message.error('验证码发送失败,请检查手机号输入是否正确');
}
});
},
//登录
login(){
var telephone = this.loginInfo.telephone;
if (!checkTelephone(telephone)) {
this.$message.error('请输入正确的手机号');
return false;
}
axios.post("/member/login.do",this.loginInfo).then((response) => {
if(response.data.flag){
//登录成功,跳转到index.html
window.location.href="member.html";
}else{
//失败,提示失败信息
this.$message.error(response.data.message);
}
});
}
}
});
</script>
</html>
//发送验证码 快速登录的时候验证码
@RequestMapping("/send4Login")
public Result send4Login(String telephone){
//给用户发送验证码
Integer validateCode = ValidateCodeUtils.generateValidateCode(6);
String value = String.valueOf(validateCode);
System.out.println(validateCode);
try {
/* SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,value);
*/ //根据业务用手机号+业务的形式保存
//将验证码保存到redis(定时间)
jedisPool.getResource().setex(telephone+ RedisMessageConstant.SENDTYPE_LOGIN,500,value);
return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
} catch (Exception e) {
e.printStackTrace();
return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
}
}
还是和昨天的类似,在Controller层多个redis存入和验证码生成,后面登录的时候业务比较复杂,一点点分析。
@RestController
@RequestMapping("/member")
public class MemberController {
@Autowired
private JedisPool jedisPool;
@Reference
private MemberService memberService;
//手机号快速登录
@RequestMapping("/login")
public Result login(HttpServletResponse httpServletResponse, @RequestBody Map map){
String telephone = (String) map.get("telephone");
String validateCode = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
String code = (String) map.get("validateCode");
if (code!=null&&validateCode!=null&&code.equals(validateCode)){
//验证成功,判断是不是会员
Member member = memberService.findByTelephone(telephone);
if (member==null){
//不是会员,自动完成注册
member.setRegTime(new Date());
member.setPhoneNumber(telephone);
memberService.add(member);
}
//向客户端浏览器写入Cookie,内容为手机号
Cookie cookie = new Cookie("login_member_telephone",telephone);
cookie.setPath("/");
cookie.setMaxAge(60*60*24*30);//30天有效期
httpServletResponse.addCookie(cookie);
//保存会员信息到Redis,同时对象需要转化成json格式
String json = JSON.toJSON(member).toString();
jedisPool.getResource().setex(telephone,60*30,json);
return new Result(true,MessageConstant.LOGIN_SUCCESS);
}else {
//验证失败
return new Result(false, MessageConstant.VALIDATECODE_ERROR);
}
}
}
1.验证用户输入的验证码是否正确,如果验证码错误则登录失败。
2.如果验证码正确,则判断当前用户是否为护院,如果不是会员则自动完成会员注册
3.向客户端写入Cookie,内容为用户手机号
4.将会员信息保存到Redis,使用手机号作为key,保存时间为30分钟。
用户怎么算登录了呢?把用户信息保存到Session中,才是真正的登录成功,因为涉及集群到共享session的情况,这里用redis做存储,先要放入cookie中,这样页面跳转的时候用户信息就不会丢失了,和之前session一样
Service和dao就不写了,比较简单,不过一点,在新增会员时对其要进行加密处理
//根据手机号查询会员
public Member findByTelephone(String telephone){
return memberDao.findByTelephone(telephone);
}
//新增会员 public void add(Member member)
{
if(member.getPassword() != null) {
member.setPassword(MD5Utils.md5(member.getPassword())); }
memberDao.add(member);
}
加密小知识
密码一定要进行加密 安全 防止泄露
RSA AES 3DES SM1-SM4
可逆:明文- ->密文 -->明文 通过密钥进行加密解密
不可逆:明文–>密文 MD5
可能会出现撞库很可怕(多个网站的账号密码是同一个)
一方面:网站(保证用户的个人资料是安全的)
环境:服务器环境
密码:加密 /加盐
xiaoming#@15
3. 权限控制
3.1 认证和授权概念
前面我们已经完成了传智健康后台管理系统的部分功能,例如检查项管理、检查组管理、套餐管理、预
约设置等。接下来我们需要思考2个问题:
问题1:在生产环境下我们如果不登录后台系统就可以完成这些功能操作吗?
答案显然是否定的,要操作这些功能必须首先登录到系统才可以。
问题2:是不是所有用户,只要登录成功就都可以操作所有功能呢?
答案是否定的,并不是所有的用户都可以操作这些功能。不同的用户可能拥有不同的权限,这就需要进
行授权了。
认证:系统提供的用于识别用户身份的功能,通常提供用户名和密码进行登录其实就是在进行认证,认
证的目的是让系统知道你是谁。
授权:用户认证成功后,需要为用户授权,其实就是指定当前用户可以操作哪些功能。
本章节就是要对后台系统进行权限控制,其本质就是对用户进行认证和授权
3.2 权限模块数据模型
前面已经分析了认证和授权的概念,要实现最终的权限控制,需要有一套表结构支撑:
用户表t_user、权限表t_permission、角色表t_role、菜单表t_menu、用户角色关系表t_user_role、角
色权限关系表t_role_permission、角色菜单关系表t_role_menu。
表之间关系如下图:
通过上图可以看到,权限模块共涉及到7张表。在这7张表中,角色表起到了至关重要的作用,其处于核
心位置,因为用户、权限、菜单都和角色是多对多关系。
授权过程:用户必须完成认证之后才可以进行授权,首先可以根据用户查询其角色,再根据角色查询对
应的菜单,这样就确定了用户能够看到哪些菜单。然后再根据用户的角色查询对应的权限,这样就确定
了用户拥有哪些权限。所以授权过程会用到上面7张表。
3.3 Spring Security简介
Spring Security是 Spring提供的安全认证服务的框架。 使用Spring Security可以帮助我们来简化认证
和授权的过程。官网:https://spring.io/projects/spring-security
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
常用的权限框架除了Spring Security,还有Apache的shiro框架
3.4实现
创就一个web工程
maven坐标
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<!-- 指定端口 -->
<port>85</port>
<!-- 请求路径 -->
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<display-name>Archetype Created Web Application</display-name>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-security.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
spring-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<!--配置哪些资源匿名可以访问(不登录也可以访问)-->
<!--<security:http security="none" pattern="/pages/a.html"></security:http>
<security:http security="none" pattern="/pages/b.html"></security:http>-->
<!--<security:http security="none" pattern="/pages/**"></security:http>-->
<security:http security="none" pattern="/login.html"></security:http>
<!--
auto-config:自动配置,如果设置为true,表示自动应用一些默认配置,比如框架会提供一个默认的登录页面
use-expressions:是否使用spring security提供的表达式来描述权限
-->
<security:http auto-config="true" use-expressions="true">
<!--配置拦截规则,/** 表示拦截所有请求-->
<!--
pattern:描述拦截规则
asscess:指定所需的访问角色或者访问权限
-->
<!--只要认证通过就可以访问-->
<security:intercept-url pattern="/pages/a.html" access="isAuthenticated()" />
<!--拥有add权限就可以访问b.html页面-->
<security:intercept-url pattern="/pages/b.html" access="hasAuthority('add')" />
<!--拥有ROLE_ADMIN角色就可以访问c.html页面-->
<security:intercept-url pattern="/pages/c.html" access="hasRole('ROLE_ADMIN')" />
<!--拥有ROLE_ADMIN角色就可以访问d.html页面,
注意:此处虽然写的是ADMIN角色,框架会自动加上前缀ROLE_-->
<security:intercept-url pattern="/pages/d.html" access="hasRole('ADMIN')" />
<security:intercept-url pattern="/**" access="hasRole('ROLE_ADMIN')"></security:intercept-url>
<!--如果我们要使用自己指定的页面作为登录页面,必须配置登录表单.页面提交的登录表单请求是由框架负责处理-->
<!--
login-page:指定登录页面访问URL
-->
<security:form-login
login-page="/login.html"
username-parameter="username"
password-parameter="password"
login-processing-url="/login.do"
default-target-url="/index.html"
authentication-failure-url="/login.html"></security:form-login>
<!--
csrf:对应CsrfFilter过滤器
disabled:是否启用CsrfFilter过滤器,如果使用自定义登录页面需要关闭此项,否则登录操作会被禁用(403)
-->
<security:csrf disabled="true"></security:csrf>
<!--
logout:退出登录
logout-url:退出登录操作对应的请求路径
logout-success-url:退出登录后的跳转页面
-->
<security:logout logout-url="/logout.do"
logout-success-url="/login.html" invalidate-session="true"/>
</security:http>
<!--配置认证管理器-->
<security:authentication-manager>
<!--配置认证提供者-->
<security:authentication-provider user-service-ref="userService2">
<!--
配置一个具体的用户,后期需要从数据库查询用户
<security:user-service>
<security:user name="admin" password="{noop}1234" authorities="ROLE_ADMIN"/>
</security:user-service>
-->
<!--指定度密码进行加密的对象-->
<security:password-encoder ref="passwordEncoder"></security:password-encoder>
</security:authentication-provider>
</security:authentication-manager>
<bean id="userService" class="com.itheima.service.SpringSecurityUserService"></bean>
<bean id="userService2" class="com.itheima.service.SpringSecurityUserService2"></bean>
<!--配置密码加密对象-->
<bean id="passwordEncoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
<!--开启spring注解使用-->
<context:annotation-config></context:annotation-config>
<mvc:annotation-driven></mvc:annotation-driven>
<context:component-scan base-package="com.itheima.controller"></context:component-scan>
<!--开启注解方式权限控制-->
<security:global-method-security pre-post-annotations="enabled" />
</beans>
SpringSecurityUserService
这里先写死,后期这些权限人物都需要从数据库中查询出来
package com.itheima.service;
import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SpringSecurityUserService implements UserDetailsService {
//模拟数据库中的用户数据
public static Map<String, User> map = new HashMap<>();
static {
com.itheima.pojo.User user1 = new com.itheima.pojo.User();
user1.setUsername("admin");
user1.setPassword("admin");//明文密码(没有加密)
com.itheima.pojo.User user2 = new com.itheima.pojo.User();
user2.setUsername("xiaoming");
user2.setPassword("1234");
map.put(user1.getUsername(),user1);
map.put(user2.getUsername(),user2);
}
//根据用户名查询用户信息
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("用户输入的用户名为:" + username);
//根据用户名查询数据库获得用户信息(包含数据库中存储的密码信息)
User user = map.get(username);//模拟查询根据用户名查询数据库
if(user == null){
//用户名不存在
return null;
}else{
//将用户信息返回给框架
//框架会进行密码比对(页面提交的密码和数据库中查询的密码进行比对)
List<GrantedAuthority> list = new ArrayList<>();
//为当前登录用户授权,后期需要改为从数据库查询当前用户对应的权限
list.add(new SimpleGrantedAuthority("permission_A"));//授权
list.add(new SimpleGrantedAuthority("permission_B"));
if(username.equals("admin")){
list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));//授予角色
}
org.springframework.security.core.userdetails.User securityUser = new org.springframework.security.core.userdetails.User(username,"{noop}"+user.getPassword(),list);
return securityUser;
}
}
}
controller
@RestController
@RequestMapping("/hello")
public class HelloController
{ @RequestMapping("/add")
@PreAuthorize("hasAuthority('add')")//表示用户必须拥有add权限才能调用当前方法
public String add()
{ System.out.println("add...");
return "success"; }
@RequestMapping("/delete")
@PreAuthorize("hasRole('ROLE_ADMIN')")//表示用户必须拥有ROLE_ADMIN角色才能调用当 前方法
public String delete(){
System.out.println("delete...");
return "success"; }
}
1.这里有个BUG,如果把密码加密器配置进去后,没有在controller中注册使用,会出现会话域存不进去,一直跳转错误页面去的
<!-- authentication-manager:认证管理器,用于处理认证操作 -->
<security:authentication-manager>
<security:authentication-provider user-service-ref="springSecurityUserService">
<!--<security:password-encoder ref="cryptPasswordEncoder"/>-->
</security:authentication-provider>
</security:authentication-manager>
<!-- 密码加密器 -->
<bean class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" id="cryptPasswordEncoder"/>
2.配置人物,授权,是否登录注意顺序!不然可能会出现问题
<security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/pages/a.html"access="hasRole('ROLE_ybb')"/>
<security:intercept-url pattern="/pages/c.html"access="hasAuthority('KANSHU')"/>
<security:intercept-url pattern="/**" access="isAuthenticated()"/>
3.存储的时候注意
4.现在访问路径都是.do结尾,手动打url时记得加入.do