本文只包涵spring security配置部分,不是一个完整项目,不过可以任意添加到一个web项目中,不需要对原来的程序做任何修改

部分内容来源于网络,如有雷同,毫无意外

1、xml配置文件

<?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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<global-method-security pre-post-annotations="enabled">
</global-method-security> <!-- 不拦截的路径 -->
<http pattern="/registerPage" security="none" />
<http pattern="/mainPage" security="none"></http>
<http pattern="/item/itemid**" security="none"></http>
<http pattern="/css/**" security="none" />
<http pattern="/font/**" security="none" />
<http pattern="/images/**" security="none" />
<http pattern="/js/**" security="none" /> <http auto-config="true">
<!-- 登录配置 -->
<form-login login-page="/loginPage"
authentication-failure-url="/login/failure"
login-processing-url="/login"
authentication-success-handler-ref="mySuccessHandler"
username-parameter="username"
password-parameter="password" /> <!-- 用户登出 -->
<logout invalidate-session="true" logout-success-url="/loginPage"
logout-url="/logout" /> <!-- 拦截页面 -->
<intercept-url pattern="/item/**" access="ROLE_USER" />
<intercept-url pattern="/admin/**" access="ROLE_USER" />
</http> <!-- 登录成功的处理方法 -->
<beans:bean id="mySuccessHandler" class="security.LoginSuccessHandle" ></beans:bean> <!-- 获取UserDettail的bean -->
<beans:bean id="UserDetailService" class="security.MyUserDetailService"></beans:bean> <!-- 在这里也是一个大坑,查询网上的文章,这里都是引用的实现了UserDetailsService的类 -->
<beans:bean id="UserService" class="security.SecurityProvider"></beans:bean>
<authentication-manager>
<authentication-provider ref="UserService">
</authentication-provider>
</authentication-manager>
</beans:beans>

2、用户权限信息类

省略相关数据库代码以及dao层代码

package po;

public class UserRole {

    private String username;
private String password;
private String role; public UserRole(String username, String password, String role) {
super();
this.username = username;
this.password = password;
this.role = role;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public String getRole() {
return role;
} public void setRole(String role) {
this.role = role;
}
}

3、MyUserDetail类,实现UserDetail接口,包含用户信息和用户权限类型

package security;

import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails; import po.UserRole; public class MyUserDetail implements UserDetails {
/**
*
*/
private static final long serialVersionUID = -5619502406659516775L;
private UserRole myUser;
private Collection<? extends GrantedAuthority> authorities; public MyUserDetail(UserRole user,Collection<? extends GrantedAuthority> authorities) {
this.myUser = user;
this.authorities = authorities;
} public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
public UserRole getMyUser() {
return myUser;
}
public String getPassword() {
return myUser.getPassword();
} public String getUsername() {
return myUser.getUsername();
} public boolean isAccountNonExpired() {
return false;
} public boolean isAccountNonLocked() {
return false;
} public boolean isCredentialsNonExpired() {
return false;
} public boolean isEnabled() {
return false;
} }

4、MyUserDetailService类,实现UserDetailsService接口,用来获取一个UserDetail对象

package security;

import java.util.ArrayList;
import java.util.Collection; 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.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service; import mapper.UserRoleMapper;
import po.UserRole; @Service
public class MyUserDetailService implements UserDetailsService {
@Autowired
UserRoleMapper userdao;
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
UserRole user =userdao.getUserByName(username);
if(user==null)
{
throw new UsernameNotFoundException("找不到该用户");
}
// Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
// SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role);
// grantedAuthorities.add(grantedAuthority);
return new MyUserDetail(user, getAuthorities(user.getRole()));
} private Collection<GrantedAuthority> getAuthorities(String role) {
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role);
grantedAuthorities.add(grantedAuthority);
return grantedAuthorities;
} }

5、SecurityProvider类,实现了AuthenticationProvider,返回一个UsernamePasswordAuthenticationToken

package security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException; public class SecurityProvider implements AuthenticationProvider {
@Autowired
private MyUserDetailService userDetailsService;
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
UserDetails userDetails = userDetailsService.loadUserByUsername(token.getName());
if (userDetails == null) {
throw new UsernameNotFoundException("找不到该用户");
}
if(!userDetails.getPassword().equals(token.getCredentials().toString()))
{
throw new BadCredentialsException("用户密码错误");
}
return new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(),userDetails.getAuthorities());
} public boolean supports(Class<?> authentication) {
return UsernamePasswordAuthenticationToken.class.equals(authentication);
} }

6、登录成功后自定义处理过程

spring security可以在配置文件中设置登录成功后的跳转页面,或者是直接返回认证前想要访问的页面,但是因为有时候用户是使用ajax请求登录,所以需要自定义一些操作,我是在登录成功后跳转到控制层url,

在url中携带需要跳转的参数,然后在控制层中将url参数返回到ajax,再由前端重新请求控制层跳转

package security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest; public class LoginSuccessHandle implements AuthenticationSuccessHandler, InitializingBean {
private RequestCache requestCache = new HttpSessionRequestCache(); @Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authen)
throws IOException, ServletException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
// 默认认证后跳转路径
String targetUrl = "/mainPage"; // 如果登录前有请求为拦截页面,则验证后跳转到该页面
if (savedRequest != null) {
targetUrl = savedRequest.getRedirectUrl();
} // 跳转到认证成功处理控制器
response.sendRedirect("/loginSuccess?url=" + targetUrl); } @Override
public void afterPropertiesSet() throws Exception {
} }

spring security的简单应用的更多相关文章

  1. spring security实现简单的url权限拦截

    在一个系统中,权限的拦截是很常见的事情,通常情况下我们都是基于url进行拦截.那么在spring security中应该怎么配置呢. 大致步骤如下: 1.用户登录成功后我们需要拿到用户所拥有的权限,并 ...

  2. Spring Security:简单的保护一个SpringBoot应用程序(总结)

    Spring Security 在 Java类中的配置 在 Spring Security 中使用 Java配置,可以轻松配置 Spring Security 而无需使用 XML . 在Spring ...

  3. Spring Security之简单举例

    核心功能 Spring Security提供了三个核心的功能: 认证(你是谁) 授权(你能干什么) 攻击防护(防止伪造身份) 一个简单例子 默认情况 在前面的开发中,都是将spring securit ...

  4. Spring Boot 2.0 利用 Spring Security 实现简单的OAuth2.0认证方式1

    0. 前言 之前帐号认证用过自己写的进行匹配,现在要学会使用标准了.准备了解和使用这个OAuth2.0协议. 1. 配置 1.1 配置pom.xml 有些可能会用不到,我把我项目中用到的所有包都贴出来 ...

  5. Spring Boot 2.0 利用 Spring Security 实现简单的OAuth2.0认证方式2

    0.前言 经过前面一小节已经基本配置好了基于SpringBoot+SpringSecurity+OAuth2.0的环境.这一小节主要对一些写固定InMemory的User和Client进行扩展.实现动 ...

  6. spring security简单教程以及实现完全前后端分离

    spring security是spring家族的一个安全框架,入门简单.对比shiro,它自带登录页面,自动完成登录操作.权限过滤时支持http方法过滤. 在新手入门使用时,只需要简单的配置,即可实 ...

  7. Spring Security OAuth2 SSO

    通常公司肯定不止一个系统,每个系统都需要进行认证和权限控制,不可能每个每个系统都自己去写,这个时候需要把登录单独提出来 登录和授权是统一的 业务系统该怎么写还怎么写 最近学习了一下Spring Sec ...

  8. 【Spring】12、Spring Security 四种使用方式

    spring security使用分类: 如何使用spring security,相信百度过的都知道,总共有四种用法,从简到深为:1.不用数据库,全部数据写在配置文件,这个也是官方文档里面的demo: ...

  9. Spring Security 源码解析(一)

    上篇 Spring Security基本配置已讲述了Spring Security最简单的配置,本篇将开始分析其基本原理 在上篇中可以看到,在访问 http://localhost:18081/use ...

随机推荐

  1. C++指针二(易错模型)

    规则一:Main(主调函数)分配的内存(在堆区,栈区.全局区)都可以在被调用函数里使用.如果在被调用函数里面的临时区(栈)分配内存,主调用函数是不能使用的. #include "stdio. ...

  2. JSP动作元素<jsp:include>和<jsp:param>的搭配使用

    最近开发项目中广告头的优化:引入了<jsp:include page="XX.jsp"></jsp:include> 当<jsp:include> ...

  3. js中对String去空格

    str为要去除空格的字符串: 去除所有空格: str = str.replace(/\s+/g,""); 去除两头空格: str = str.replace(/^\s+|\s+$/ ...

  4. activity之间如何传递list

    可以把list的内容拼成json串再去解析

  5. 声笔飞码GB2312单字效率分析

    -----------------------声笔飞码强字方式单字效率分析-------------------------- 2   keys: 567       items, 381900209 ...

  6. Allegro中常见的文件格式

    allegro/APD.jrl : 记录开启 Allegro/APD 期间每一个执行动作的 command .产生在每一次新开启 Allegro/APD 的现行工作目录下 .env : 存在 pcbe ...

  7. 前端开发 - HTML/CSS

    概述 HTML是英文HyperText Mark-up Language(超文本标记语言)的缩写,他是一种制作万维网页面标准语言(标记). 相当于定义统一的一套规则,大家都来遵守他,这样就可以让浏览器 ...

  8. 微信内置浏览器私有接口WeixinJSBridge介绍

    原文地址:http://www.3lian.com/edu/2015/05-25/216227.html 这篇文章主要介绍了微信内置浏览器私有接口WeixinJSBridge介绍,本文讲解了发送给好友 ...

  9. Android-HttpClient-Get与Post请求登录功能

    HttpClient 是org.apache.http.* 包中的: 第一种方式使用httpclient-*.jar (需要在网上去下载httpclient-*.jar包) 把httpclient-4 ...

  10. title

    事实上 @import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css);@import ur ...