本文只包涵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. bzoj1242(弦图判定)

    cdqppt地址:https://wenku.baidu.com/view/a2bf4ad9ad51f01dc281f1df.html: 代码实现参考的http://blog.csdn.net/u01 ...

  2. php excel

    项目中需要把excel转为索引数组,不输出key 只说下普世技巧 找了php excel插件 发现需要createReader方法,在sublime中search,可以搜索文件内容,找到使用creat ...

  3. DB2 Sql性能查看与优化

    1.执行次数最多的TOP10SQL"db2 "select * from sysibmadm.snapdyn_sql order by NUM_EXECUTIONS desc fe ...

  4. Azure DevOps Server (TFS)中代码文件换行问题解决方案(Git)

    之前写过一篇博客"探索TFS Git 库文件换行(CRLF)的处理方式",主要是针对TFVC代码库的. 下面这篇文章说明如何在TFS的Git库中处理代码换行的问题. 概述 在Azu ...

  5. .NET MVC 学习笔记(五)— Data Validation

    .NET MVC 学习笔记(五)—— Data Validation 在实际应用中,我们需要对数据进行增查改删业务,在添加和修改过程中,无论你编写什么样的网页程序,都需要对用户的数据进行验证,以确数据 ...

  6. JQuery Mobile - 解决页面点击时候,页眉和页脚消失问题!

    当点击页面时候,页眉和页脚会消失!解决方法,在页面和页脚中加入: data-quicklinks="true" 实际使用代码: <div data-role="pa ...

  7. C/C++掌握技能(一)

    1.在编译器中输入代码并将其保存为.cpp文件(C语言的文件扩展名.c,但为了使用C++中的一些好用的特性,请把文件扩展名改为C++的.cpp)2.等价头文件:#include<stdio.h& ...

  8. Postgres 的 Range 类型

    mysql 不支持 Range 类型 零.介绍 1. 适用场景: a.可以用于实现 是否满足薪资需求 的功能 b.可以用于实现 是否符合上线时间 的功能 一.定义 1.类型范围 Postgres Se ...

  9. Windows平台下搭建自己的Git服务器

    该文章转自:http://www.codeceo.com/article/windows-git-server.html Gitblit 是一个纯 Java 库用来管理.查看和处理 Git 资料库,相 ...

  10. POJ 2603

    #include<iostream> #include<stdio.h> #define M 350000 #define N 30000 using namespace st ...