博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring security的简单应用
阅读量:5371 次
发布时间:2019-06-15

本文共 7222 字,大约阅读时间需要 24 分钟。

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

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

 

1、xml配置文件

 

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
authorities; public MyUserDetail(UserRole user,Collection
authorities) { this.myUser = user; this.authorities = authorities; } public Collection
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;@Servicepublic 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
grantedAuthorities = new ArrayList<>();// SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role);// grantedAuthorities.add(grantedAuthority); return new MyUserDetail(user, getAuthorities(user.getRole())); } private Collection
getAuthorities(String role) { Collection
grantedAuthorities = new ArrayList
(); 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 {    }}

 

转载于:https://www.cnblogs.com/yyxxn/p/8257850.html

你可能感兴趣的文章
用表单写兴趣爱好的程序
查看>>
winform程序操作或执行javascript程序
查看>>
如果将markdown视作一门编程语言可以做哪些有趣的事情?
查看>>
第三次作业
查看>>
数据结构--树
查看>>
underline
查看>>
主要日期函数的分类
查看>>
Glide 下载Gif文件
查看>>
全排列
查看>>
c# 对SOAP返回XML字符串的解析方法
查看>>
线程Thread
查看>>
最长公共子串_暴力解法(不会正解)36行
查看>>
摆棋子
查看>>
冲刺二------个人任务
查看>>
[HIve - LanguageManual] Joins
查看>>
unity里的c#
查看>>
UMLl类图实例
查看>>
java随机汉字生成
查看>>
Win7 “Bluetooth设置”对话框无法打开,及无法查找到设备
查看>>
"Coding Interview Guide" -- 在行列都排好序的矩阵中找数
查看>>