品优购项目笔记(十二)
用户中心
用户注册流程
实现短信验证码注册功能
一、controller中两个方法
- 发送验证码
- 注册
@RestController
@RequestMapping("/user")
public class UserController {
@Reference
private UserService userService;
@RequestMapping("/sendCode")
public Result sendCode(String phone){
try {
if (phone==null || "".equals(phone)){
return new Result(false,"手机号不能为空!");
}
if (!PhoneFormatCheckUtils.isPhoneLegal(phone)){
return new Result(false, "手机号格式不正确!");
}
userService.sendCode(phone);
return new Result(true,"验证码发送成功!");
} catch (Exception e) {
e.printStackTrace();
return new Result(false,"验证码发送失败!");
}
}
@RequestMapping("/add")
public Result add(@RequestBody User user, String smscode){
try {
if (userService.checkCode(user.getPhone(),smscode)){
user.setCreated(new Date());
user.setUpdated(new Date());
user.setSourceType("1");
user.setStatus("Y");
userService.add(user);
return new Result(true,"用户注册成功!");
}
return new Result(false,"用户注册失败!");
} catch (Exception e) {
e.printStackTrace();
return new Result(false,"用户注册失败!");
}
}
}
二、三个服务
- 给消息服务器发送手机号、验证码、模板和签名的消息
- 校验验证码是否正确
- 将user对象添加到数据库
@Service
public class UserServiceImpl implements UserService {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private JmsTemplate jmsTemplate;
@Autowired
private ActiveMQQueue smsDestination;
@Autowired
private UserDao userDao;
@Value("${template_code}")
private String template_code;
@Value("${sign_name}")
private String sign_name;
@Override
public void sendCode(final String phone) {
//1.随机生成6位的数字
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 6; i++) {
int b = new Random().nextInt(10);
sb.append(b);
}
final String code = sb.toString();
//2.将生成的验证码放入redis中,并设置时间为10分钟
redisTemplate.boundValueOps(phone).set(code, 60 * 10 , TimeUnit.SECONDS);
//3.将信息发送给消息服务器
jmsTemplate.send(smsDestination, new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
MapMessage message = session.createMapMessage();
message.setString("mobile", phone);
message.setString("template_code", template_code);
message.setString("sign_name", sign_name);
Map map = new HashMap();
map.put("code",code);
message.setString("param", JSON.toJSONString(map));
return (Message) message;
}
});
}
@Override
public Boolean checkCode(String phone, String smscode) {
//1.判断手机号和验证码是否为空
if (phone==null || smscode==null || "".equals(phone) || "".equals(smscode)){
return false;
}
//2.从redis中取出验证码
String code = (String) redisTemplate.boundValueOps(phone).get();
//3.进行验证
if (smscode.equals(code)){
return true;
}
return false;
}
@Override
public void add(User user) {
userDao.insertSelective(user);
}
}
单点登录
介绍
单点登录又叫做sso,是在互相信任的多个系统中,只需要输入一次密码,就可以直接登录其他互相信任的系统。
使用的原因:tomcat的session无法跨tomcat使用
使用场景:
- 传统企业项目: 做系统权限集成
- 互联网项目: soa分布式架构下, 是多个项目, 如果跨项目跳转访问能够自动认证.
不使用框架实现流程
cas框架
cas是耶鲁大学的一个开源项目,cas是单点登录的一个解决方案。
优点:基本可以不写代码,就可以实现单点登录。
原理:cas是一个现成的项目,部署到linux系统形成单点登录服务器,项目中配置cas客户端工具包,就可以不写代码实现单点登录。
cas运行流程
和不使用框架时的流程基本相同
单点登录流程
一、配置两个项目,并发布到两个不同的tomcat上
二、添加依赖
<!-- cas -->
<dependency>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-core</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
三、在web.xml中添加配置,注意两个tomcat的端口不能重复,需要进行修改
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!-- 用于单点退出,该过滤器用于实现单点登出功能,可选配置 -->
<listener>
<listener-class>org.jasig.cas.client.session.SingleSignOutHttpSessionListener</listener-class>
</listener>
<!-- 该过滤器用于实现单点登出功能,可选配置。 -->
<filter>
<filter-name>CAS Single Sign Out Filter</filter-name>
<filter-class>org.jasig.cas.client.session.SingleSignOutFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CAS Single Sign Out Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 该过滤器负责用户的认证工作,必须启用它 -->
<filter>
<filter-name>CASFilter</filter-name> <filter-class>org.jasig.cas.client.authentication.AuthenticationFilter</filter-class>
<init-param>
<param-name>casServerLoginUrl</param-name>
<param-value>http://192.168.200.128:9100/cas/login</param-value>
<!--这里的server是服务端的IP -->
</init-param>
<init-param>
<param-name>serverName</param-name>
<param-value>http://localhost:9001</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CASFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 该过滤器负责对Ticket的校验工作,必须启用它 -->
<filter>
<filter-name>CAS Validation Filter</filter-name>
<filter-class> org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter</filter-class>
<init-param>
<param-name>casServerUrlPrefix</param-name>
<param-value>http://192.168.200.128:9100/cas</param-value>
</init-param>
<init-param>
<param-name>serverName</param-name>
<param-value>http://localhost:9001</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CAS Validation Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 该过滤器负责实现HttpServletRequest请求的包裹, 比如允许开发者通过HttpServletRequest的getRemoteUser()方法获得SSO登录用户的登录名,可选配置。 -->
<filter>
<filter-name>CAS HttpServletRequest Wrapper Filter</filter-name>
<filter-class>
org.jasig.cas.client.util.HttpServletRequestWrapperFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CAS HttpServletRequest Wrapper Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 该过滤器使得开发者可以通过org.jasig.cas.client.util.AssertionHolder来获取用户的登录名。 比如AssertionHolder.getAssertion().getPrincipal().getName()。 -->
<filter>
<filter-name>CAS Assertion Thread Local Filter</filter-name> <filter-class>org.jasig.cas.client.util.AssertionThreadLocalFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CAS Assertion Thread Local Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
四、运行流程
当根据地址访问第一个项目时,会跳转到cas认证服务器,当输入账号密码正确时,跳转到之前访问的地址,并在地址栏中带上jsession。
再次访问第二个项目,此时不用进行认证直接跳转到第二个项目的首页。
注销
在cas的cas-servlet.xml中,将以下的false改为true
<bean id="logoutAction" class="org.jasig.cas.web.flow.LogoutAction"
p:servicesManager-ref="servicesManager"
p:followServiceRedirects="${cas.logout.followServiceRedirects:true}"/>
然后在页面中添加一个超链接,注销并跳转百度
<a href="http://192.168.200.128:9100/cas/logout?service=http://www.baidu.com">退出登录</a>
cas服务器连接mysql进行认证
一、首先,需要让mysql能够远程进行访问。注意修改完权限之后需要刷新权限
二、修改cas服务端中web-inf下deployerConfigContext.xml
,添加如下配置
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
p:driverClass="com.mysql.jdbc.Driver"
p:jdbcUrl="jdbc:mysql://192.168.200.128:3306/pinyougoudb?characterEncoding=utf8"
p:user="root"
p:password="admin" />
<bean id="passwordEncoder"
class="org.jasig.cas.authentication.handler.DefaultPasswordEncoder"
c:encodingAlgorithm="MD5"
p:characterEncoding="UTF-8" />
<bean id="dbAuthHandler"
class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler"
p:dataSource-ref="dataSource"
p:sql="select password from tb_user where username = ?"
p:passwordEncoder-ref="passwordEncoder"/>
三、注释掉自带的账号密码,添加数据库中的账号密码
<bean id="authenticationManager" class="org.jasig.cas.authentication.PolicyBasedAuthenticationManager">
<constructor-arg>
<map>
<entry key-ref="proxyAuthenticationHandler" value-ref="proxyPrincipalResolver" />
<!-- <entry key-ref="primaryAuthenticationHandler" value-ref="primaryPrincipalResolver" />
<entry key-ref="dbAuthHandler" value-ref="primaryPrincipalResolver"/>
</map>
</constructor-arg>
<property name="authenticationPolicy">
<bean class="org.jasig.cas.authentication.AnyAuthenticationPolicy" />
</property>
</bean>
注释掉
<entry key-ref="primaryAuthenticationHandler" value-ref="primaryPrincipalResolver" />
添加
<entry key-ref="dbAuthHandler" value-ref="primaryPrincipalResolver"/>
cas服务器登陆页面改造
一、将css、js等静态资源拷贝到cas中
二、将登陆页面login.html拷贝到cas系统下WEB-INF\view\jsp\default\ui
目录下,并将原来的casLoginView.jsp 改名(可以为之后的修改操作做参照),将login.html改名为casLoginView.jsp
三、修改页面内容
- 添加指令
在页面顶部添加
<%@ page pageEncoding="UTF-8" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
- 修改form标签
<form:form method="post" id="fm1" commandName="${commandName}" htmlEscape="true" class="sui-form">
......
</form:form>
- 修改用户名输入框
<form:input id="username" tabindex="1"
accesskey="${userNameAccessKey}" path="username" autocomplete="off" htmlEscape="true"
placeholder="邮箱/用户名/手机号" class="span2 input-xfat" />
- 修改密码框
<form:password id="password" tabindex="2" path="password"
accesskey="${passwordAccessKey}" htmlEscape="true" autocomplete="off"
placeholder="请输入密码" class="span2 input-xfat" />
- 修改登陆按钮
<input type="hidden" name="lt" value="${loginTicket}" />
<input type="hidden" name="execution" value="${flowExecutionKey}" />
<input type="hidden" name="_eventId" value="submit" />
<input class="sui-btn btn-block btn-xlarge btn-danger" accesskey="l" value="登陆" type="submit" />
完成
登陆页面错误信息
一、在form:form标签下,添加一行
<form:errors path="*" id="msg" cssClass="errors" element="div" htmlEscape="false" />
但此时,错误提示信息为英文
二、修改错误信息为中文
修改修改cas-servlet.xml
,将en改为zh_CN
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" p:defaultLocale="zh_CN" />
并在classes/messages_zh_CN.properties中,添加错误信息
authenticationFailure.AccountNotFoundException=\u7528\u6237\u4E0D\u5B58\u5728.
authenticationFailure.FailedLoginException=\u5BC6\u7801\u9519\u8BEF.
完成!
cas和springsecurity整合
spring-security配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<http pattern="/css/**" security="none"></http>
<http pattern="/img/**" security="none"></http>
<http pattern="/js/**" security="none"></http>
<http pattern="/plugins/**" security="none"></http>
<http pattern="/register.html" security="none"></http>
<http pattern="/user/add.do" security="none"></http>
<http pattern="/user/sendCode.do" security="none"></http>
<!-- entry-point-ref 入口点引用 -->
<http use-expressions="false" entry-point-ref="casProcessingFilterEntryPoint">
<intercept-url pattern="/**" access="ROLE_USER"/>
<csrf disabled="true"/>
<!-- custom-filter为过滤器, position 表示将过滤器放在指定的位置上,before表示放在指定位置之前 ,after表示放在指定的位置之后 -->
<custom-filter ref="casAuthenticationFilter" position="CAS_FILTER" />
<custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER"/>
<custom-filter ref="singleLogoutFilter" before="CAS_FILTER"/>
</http>
<!-- CAS入口点 开始 -->
<beans:bean id="casProcessingFilterEntryPoint" class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">
<!-- 单点登录服务器登录URL -->
<beans:property name="loginUrl" value="http://192.168.200.128:9100/cas/login"/>
<beans:property name="serviceProperties" ref="serviceProperties"/>
</beans:bean>
<beans:bean id="serviceProperties" class="org.springframework.security.cas.ServiceProperties">
<!--service 配置自身工程的根地址+/login/cas -->
<beans:property name="service" value="http://localhost:8083/login/cas"/>
</beans:bean>
<!-- CAS入口点 结束 -->
<!-- 认证过滤器 开始 -->
<beans:bean id="casAuthenticationFilter" class="org.springframework.security.cas.web.CasAuthenticationFilter">
<beans:property name="authenticationManager" ref="authenticationManager"/>
</beans:bean>
<!-- 认证管理器 -->
<authentication-manager alias="authenticationManager">
<authentication-provider ref="casAuthenticationProvider">
</authentication-provider>
</authentication-manager>
<!-- 认证提供者 -->
<beans:bean id="casAuthenticationProvider" class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
<beans:property name="authenticationUserDetailsService">
<beans:bean class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<beans:constructor-arg ref="userDetailsService" />
</beans:bean>
</beans:property>
<beans:property name="serviceProperties" ref="serviceProperties"/>
<!-- ticketValidator 为票据验证器 -->
<beans:property name="ticketValidator">
<beans:bean class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator">
<beans:constructor-arg index="0" value="http://192.168.200.128:9100/cas"/>
</beans:bean>
</beans:property>
<beans:property name="key" value="an_id_for_this_auth_provider_only"/>
</beans:bean>
<!-- 认证类 -->
<beans:bean id="userDetailsService" class="cn.itcast.core.service.UserDetailsServiceImpl"/>
<!-- 认证过滤器 结束 -->
<!-- 单点登出 开始 -->
<beans:bean id="singleLogoutFilter" class="org.jasig.cas.client.session.SingleSignOutFilter"/>
<!-- 经过此配置,当用户在地址栏输入本地工程 /logout/cas -->
<beans:bean id="requestSingleLogoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
<beans:constructor-arg value="http://192.168.200.128:9100/cas/logout?service=http://localhost:8083"/>
<beans:constructor-arg>
<beans:bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>
</beans:constructor-arg>
<beans:property name="filterProcessesUrl" value="/logout/cas"/>
</beans:bean>
<!-- 单点登出 结束 -->
</beans:beans>
UserDetailsServiceImpl类,只负责赋权,所以传递密码时传递""
public class UserDetailsServiceImpl implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
return new User(username,"",authorities);
}
}