品優購項目筆記(十二)
用戶中心
用戶註冊流程
實現短信驗證碼註冊功能
一、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);
}
}