先看官方文档:http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/

spring security4已经加入了注解的方式,但是为了比较清晰了解,还是使用了配置的方式。

第一步:web.xml 加入拦截、

    <!-- 配置springSecurityFilter -->
<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>

第二步:编写配置文件:spring-security.xml

<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-3.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd ">
<http pattern="/common/**" security="none" />
<http pattern="/login.jsp" security="none" />
<http pattern="/user/login" security="none" />
<http pattern="/index" security="none" />
<http use-expressions="true">
<intercept-url pattern="/**" access="isAuthenticated()" />
<form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?error=1" />
<logout invalidate-session="true" logout-url="/logout" logout-success-url="/" />
</http>
<authentication-manager alias="myAuthenticationManager">
<authentication-provider user-service-ref="cwSysUserDetailsService">
<password-encoder hash="md5"></password-encoder>
</authentication-provider>
</authentication-manager> </beans:beans>

第三步:编写登录认证函数

package com.eshore.upsweb.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service; import com.eshore.upsweb.dao.CwSysUserDAO;
import com.eshore.upsweb.model.CwSysUser;
import com.eshore.upsweb.model.CwSysUserRole; @Service(value="cwSysUserDetailsService")
public class CwSysUserDetailsService implements UserDetailsService{ @Autowired
CwSysUserDAO cwSysUserDAO; @Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
System.out.println("username is " + username);
CwSysUser user = cwSysUserDAO.findUser(username);
List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRoles());
return buildUserForAuthentication(user, authorities);
} /**
* 返回验证角色
* @param userRoles
* @return
*/
private List<GrantedAuthority> buildUserAuthority(Set<CwSysUserRole> userRoles){
Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
for(CwSysUserRole userRole:userRoles){
setAuths.add(new SimpleGrantedAuthority(userRole.getRole().getRoleId().toString()));
}
List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(setAuths);
return result;
} /**
* 返回验证用户
* @param user
* @param authorities
* @return
*/
private User buildUserForAuthentication(CwSysUser user,List<GrantedAuthority> authorities){
return new User(user.getUserNo(),user.getPassword(),true,true,true,true,authorities);
} /**
*
*/ }

第四步:编写登录controller

package com.eshore.upsweb.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import com.eshore.upsweb.model.CwSysUser;
import com.eshore.upsweb.model.LoginInfo;
import com.eshore.upsweb.service.CwSysUserService; @Controller
@RequestMapping(value="/user")
public class CwSysUserController {
@Autowired
private CwSysUserService cwSysUserService;
@Autowired
private AuthenticationManager myAuthenticationManager; // 这样就可以自动注入?oh ,mygod ,how can it do so? @RequestMapping(value="/login",method=RequestMethod.POST)
@ResponseBody
public LoginInfo login(@RequestParam(defaultValue="") String username,@RequestParam(defaultValue="") String password,HttpServletRequest request){
if(!checkValidateCode(request)){
return new LoginInfo().failed().msg("验证码错误!");
}
username = username.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
/* DetachedCriteria detachedCriteria = DetachedCriteria.forClass(CwSysUser.class,"cwSysUser");
detachedCriteria.add(Restrictions.eq("userNo", username));
if(cwSysUserService.countUser(detachedCriteria)==0){
return new LoginInfo().failed().msg("用户名: "+username+" 不存在.");
}
*/ try {
Authentication authentication = myAuthenticationManager.authenticate(authRequest); //调用loadUserByUsername
SecurityContextHolder.getContext().setAuthentication(authentication);
HttpSession session = request.getSession();
session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext()); // 这个非常重要,否则验证后将无法登陆
return new LoginInfo().success().msg(authentication.getName());
} catch (AuthenticationException ex) {
return new LoginInfo().failed().msg("用户名或密码错误");
}
} /**
* 验证码判断
* @param request
* @return
*/
protected boolean checkValidateCode(HttpServletRequest request) {
String result_verifyCode = request.getSession().getAttribute("verifyResult")
.toString(); // 获取存于session的验证值
// request.getSession().setAttribute("verifyResult", null);
String user_verifyCode = request.getParameter("verifyCode");// 获取用户输入验证码
if (null == user_verifyCode || !result_verifyCode.equalsIgnoreCase(user_verifyCode)) {
return false;
}
return true;
} }

第五步:编写对应的登录jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>
<link href="./common/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="./common/bootstrap/css/bootstrap-theme.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="./common/css/demo.css">
<link rel="stylesheet" type="text/css" href="./common/css/style.css">
<link rel="stylesheet" type="text/css" href="./common/css/animate-custom.css">
<link rel="stylesheet" href="./common/bootstrap/css/bootstrap.css" type="text/css"></link>
<script type="text/javascript" src="./common/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="./common/jquery/jquery-2.1.1.min.js"></script>
<body>
<div class="container">
<header> </header>
<div id="container_demo">
<div id="wrapper">
<div id="login" class="animate form">
<!-- <form name='loginForm' action="<c:url value='j_spring_security_check' />" method='POST'> -->
<h1>电信融合支付平台</h1>
<form id='loginForm' method="POST">
<p>
<label for="" class="uname" data-icon="u"> 用户名 </label>
<input id="username" name="username" required="required" type="text" placeholder="myusername or mymail@mail.com">
</p>
<p>
<label for="" class="youpasswd" data-icon="p"> 密码 </label>
<input id="password" name="password" required="required" type="password" placeholder="eg. X8df!90EO">
</p>
<p>
<label for="verification" class="verification" data-icon="v"> 验证 </label>
<img src="index" id="verify" align="middle" title="看不清,请点我" style="cursor:hand;"/><br/>
<input type="verification" id="verifyCode" name="verifyCode" placeholder="验证码" required="required">
</p>
<!--
<p class="keeplogin">
<input type="checkbox" name="loginkeeping" id="loginkeeping" value="loginkeeping">
<label for="loginkeeping">保持登录</label>
</p>
-->
<p class="login button">
<input type="submit" id="submitId" value="登录">
</p>
</form>
</div>
</div>
</div>
</body> <script type="text/javascript">
$(function(){
/////////////////登录提交////////////////////////////
$("#loginForm").submit(function() {
var username=$("#username").val();
var password=$("#password").val();
var verifyCode=$("#verifyCode").val();
var data={username:username,password:password,verifyCode:verifyCode};
var url="/upsweb/user/login";
$.ajax({
type: "POST",
url: url,
data: data,
// contentType: "application/json",
dataType: "json",
success:function (result) {
if(result.ok){
location.href="/upsweb";
}else{
$(".error").remove();
$("#loginForm").prepend("<div class='error'><font color='red'>"+result.msg+"</font></div>");
$("#verify").attr("src","/upsweb/index?timestamp="+new Date().getTime()); // 刷新验证码
}
},
error:function(XMLHttpRequest, textStatus, errorThrown){
// alert(XMLHttpRequest.status);
// alert(XMLHttpRequest.readyState);
// alert(textStatus);
//alert(XMLHttpRequest.responseText);
alert('读取超时,请检查网络连接');
}
});
return false;
});
///////////////////验证码更新/////////////
$("#verify").click(function(){
$(this).attr("src","/upsweb/index?timestamp="+new Date().getTime());
}); }); $(function ()
{ $("#dd").popover();
});
</script>
</html>

简单说说Spring Security 使用(附加验证码登录,自定义认证)的更多相关文章

  1. Spring Security 实现手机验证码登录

    思路:参考用户名密码登录过滤器链,重写认证和授权 示例如下(该篇示例以精简为主,演示主要实现功能,全面完整版会在以后的博文中发出): 由于涉及内容较多,建议先复制到本地工程中,然后在细细研究. 1. ...

  2. Spring Security 一键接入验证码登录和小程序登录

    最近实现了一个多端登录的Spring Security组件,用起来非常丝滑,开箱即用,可插拔,而且灵活性非常强.我觉得能满足大部分场景的需要.目前完成了手机号验证码和微信小程序两种自定义登录,加上默认 ...

  3. Spring Security和JWT实现登录授权认证

     目标 1.Token鉴权 2.Restful API 3.Spring Security+JWT 开始 自行新建Spring Boot工程 引入相关依赖 <dependency> < ...

  4. Spring Security 前后端分离登录,非法请求直接返回 JSON

    hello 各位小伙伴,国庆节终于过完啦,松哥也回来啦,今天开始咱们继续发干货! 关于 Spring Security,松哥之前发过多篇文章和大家聊聊这个安全框架的使用: 手把手带你入门 Spring ...

  5. Spring Security OAuth2 微服务认证中心自定义授权模式扩展以及常见登录认证场景下的应用实战

    一. 前言 [APP 移动端]Spring Security OAuth2 手机短信验证码模式 [微信小程序]Spring Security OAuth2 微信授权模式 [管理系统]Spring Se ...

  6. Spring Security之多次登录失败后账户锁定功能的实现

    在上一次写的文章中,为大家说到了如何动态的从数据库加载用户.角色.权限信息,从而实现登录验证及授权.在实际的开发过程中,我们通常会有这样的一个需求:当用户多次登录失败的时候,我们应该将账户锁定,等待一 ...

  7. Spring Security 实战干货:实现自定义退出登录

    文章目录 1. 前言 2. 我们使用 Spring Security 登录后都做了什么 2. 退出登录需要我们做什么 3. Spring Security 中的退出登录 3.1 LogoutFilte ...

  8. 七:Spring Security 前后端分离登录,非法请求直接返回 JSON

    Spring Security 前后端分离登录,非法请求直接返回 JSON 解决方案 在 Spring Security 中未获认证的请求默认会重定向到登录页,但是在前后端分离的登录中,这个默认行为则 ...

  9. Spring Security 入门(1-3-1)Spring Security - http元素 - 默认登录和登录定制

    登录表单配置 - http 元素下的 form-login 元素是用来定义表单登录信息的.当我们什么属性都不指定的时候 Spring Security 会为我们生成一个默认的登录页面. 如果不想使用默 ...

  10. Spring Security入门(2-3)Spring Security 的运行原理 4 - 自定义登录方法和页面

    参考链接,多谢作者: http://blog.csdn.net/lee353086/article/details/52586916 http元素下的form-login元素是用来定义表单登录信息的. ...

随机推荐

  1. Windows下编程--模拟时钟的实现

    windows下编程--模拟时钟的实现: 主要可以分为几个步骤: (1)   编写按键事件处理(启动和停止时钟) (2)   编写时钟事件处理,调用显示时钟函数 (3)   编写显示时钟函数,要调用显 ...

  2. JAVA 方法 和Scanner

    方法:包含于类或对象中,是解决一类问题步骤的有序组合. 算法:解决一类问题的思想. Scanner next()与nextLine()区别 next(): 1.一定要读取到有效字符后才可以结束输入. ...

  3. MySQL---2、安装与部署

    1.MySQL下载 MySQL版本的选择MySQL Community Server 社区版本,开源免费,但不提供官方技术支持.MySQL Enterprise Edition 企业版本,需付费,可以 ...

  4. sql server web管理软件

    Sql server目前虽然没有mysql用户量大,但是微软的产品在易用性方面还是很不错的,有些政务类的项目还是用 Sql server数据库的, 目前有一款Sql server的web管理工具Tre ...

  5. lumen配置日志daily模式

    默认的日志保存模式是single 也就是单文件模式 要想改成每日的daily模式可以在bootstrap/app.php下添加: /* * 配置日志文件为每日 */ $app->configur ...

  6. Delegate背后的秘密

    表面上看来使用delegate是一件很简单的事. 用delegate关键字定义,使用老套的new创建一个instance ,使用熟悉的方法调用写法调用,只不过不在是方法名,而是委托名. 但是在这背后C ...

  7. C#学习笔记-原型模式

    题目:编写基本的简历. 实现: 创建基本的Resume类,然后主函数通过实例化Resume来写简历即可. Resume类: class Resume { private string name; pr ...

  8. JS深拷贝继承

    所谓深拷贝,就是子对象不紧继承父对象的非引用属性,还能继承父对象的引用属性(Object,Array),当子对象对继承的引用类型属性做修改时,父对象的引用类型不会被修改. 我们先写个浅拷贝的封装函数: ...

  9. 剑指Offer-编程详解-二维数组中的查找

    题目描述 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数 ...

  10. QT5.9 新特性与版本回顾

    原文链接: http://blog.qt.io/blog/2017/05/31/qt-5-9-released 翻译内容如下,采用的是第三方某在线翻译软件,所以有些地方不是太精确,纵然大吉做了一定的调 ...