成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

springSecurity02(mybatis+springmvc+spring) 01

FrancisSoung / 1491人閱讀

摘要:建立一個模塊繼承上一個模塊然后添加依賴解決打包時找不到文件建立數(shù)據(jù)源文件數(shù)據(jù)庫連接相關(guān)修改配置數(shù)據(jù)源和整合,以及事務(wù)管理自動掃描掃描時跳過注解的類控制器掃描配置文件這里指向的是

1.建立一個模塊繼承上一個模塊然后添加依賴

  

        
            junit
            junit
            4.11
            test
        
        
            org.springframework
            spring-test
            4.2.8.RELEASE
        
        
            org.mybatis
            mybatis
            3.4.4
        
        
            org.mybatis
            mybatis-spring
            1.3.0
        
        
            com.alibaba
            druid
            1.1.8
        
        
            mysql
            mysql-connector-java
            5.1.41
        
    
  
    
    
        
            
                src/main/java
                
                    **/*.xml
                
            
        
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    1.8
                    1.8
                
            
        
    

2.建立數(shù)據(jù)源文件application.properties

#數(shù)據(jù)庫連接相關(guān)
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/security-demo?useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.username = root
jdbc.password = 123456

3.修改applicationContext.xml,配置數(shù)據(jù)源,和mybatis整合,以及事務(wù)管理




    
    
        
        
        
    

    
    

    
    
          
             
           
           
              
               
              
          
    

    
    
        
        
        
        
    

    
    
        
    

   
    
        
    
    
    

目錄結(jié)構(gòu),我這里測試mybatis時放在同一包出問題,所以選擇了分別掃描xml和mapper接口

數(shù)據(jù)庫,總共建立了5張表,用戶表,角色表,用戶角色對應(yīng)表,權(quán)限表,權(quán)限角色對應(yīng)表,關(guān)系也很簡單,一個用戶有多個角色,一個角色也可以有多個用戶擁有,一個角色有多種權(quán)限,一個權(quán)限也可以由多個角色掌握,這個看自己怎么設(shè)計,其中用戶表最重要,這里面包含了用戶的基本信息

/*
Navicat MySQL Data Transfer

Source Server         : security
Source Server Version : 50719
Source Host           : localhost:3306
Source Database       : security-demo

Target Server Type    : MYSQL
Target Server Version : 50719
File Encoding         : 65001

Date: 2019-08-02 10:25:48
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for sys_authorization
-- ----------------------------
DROP TABLE IF EXISTS `sys_authorization`;
CREATE TABLE `sys_authorization` (
  `id` int(11) NOT NULL,
  `authorizationName` varchar(50) DEFAULT NULL,
  `authorizationMark` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of sys_authorization
-- ----------------------------
INSERT INTO `sys_authorization` VALUES ("1", "產(chǎn)品查詢", "ROLE_LIST_PRODUCT");
INSERT INTO `sys_authorization` VALUES ("2", "產(chǎn)品添加", "ROLE_ADD_PRODUCT");
INSERT INTO `sys_authorization` VALUES ("3", "產(chǎn)品修改", "ROLE_UPDATE_PRODUCT");
INSERT INTO `sys_authorization` VALUES ("4", "產(chǎn)品刪除", "ROLE_DELETE_PRODUCT");

-- ----------------------------
-- Table structure for sys_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
  `id` int(11) NOT NULL,
  `roleName` varchar(50) DEFAULT NULL,
  `roleDescription` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of sys_role
-- ----------------------------
INSERT INTO `sys_role` VALUES ("1", "普通用戶", "普通用戶");
INSERT INTO `sys_role` VALUES ("2", "管理員", "管理員");

-- ----------------------------
-- Table structure for sys_role_authorization
-- ----------------------------
DROP TABLE IF EXISTS `sys_role_authorization`;
CREATE TABLE `sys_role_authorization` (
  `roleId` int(11) NOT NULL,
  `authorizationId` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of sys_role_authorization
-- ----------------------------
INSERT INTO `sys_role_authorization` VALUES ("1", "1");
INSERT INTO `sys_role_authorization` VALUES ("1", "2");
INSERT INTO `sys_role_authorization` VALUES ("2", "1");
INSERT INTO `sys_role_authorization` VALUES ("2", "2");
INSERT INTO `sys_role_authorization` VALUES ("2", "3");
INSERT INTO `sys_role_authorization` VALUES ("2", "4");

-- ----------------------------
-- Table structure for sys_user
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `password` varchar(100) DEFAULT NULL,
  `realname` varchar(50) DEFAULT NULL,
  `createDate` date DEFAULT NULL,
  `lastLoginTime` date DEFAULT NULL,
  `enabled` int(11) DEFAULT NULL,
  `accountNonExpired` int(11) DEFAULT NULL,
  `accountNonLocked` int(11) DEFAULT NULL,
  `credentialsNonExpired` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of sys_user
-- ----------------------------
INSERT INTO `sys_user` VALUES ("1", "jojo", "$2a$10$VCvgzml/DNzBTkjsPlImDuZp38sNZB7cEmsNgFIWBm/Vtpn0Q3Bj.", "張三", "2019-06-26", "2019-08-01", "1", "1", "1", "1");
INSERT INTO `sys_user` VALUES ("2", "jack", "$2a$10$W1T2Z5dUMIgBfxvFdBOWuusq8Nwke/cQydxDFemsbTh0PjGeZCiMC", "李四", "2019-07-30", "2019-08-01", "1", "1", "1", "1");

-- ----------------------------
-- Table structure for sys_user_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_user_role`;
CREATE TABLE `sys_user_role` (
  `userId` int(11) NOT NULL,
  `roleId` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of sys_user_role
-- ----------------------------
INSERT INTO `sys_user_role` VALUES ("1", "1");
INSERT INTO `sys_user_role` VALUES ("2", "2");

基本配置完成
在mapper文件夾下建立UserMapper接口

package com.ty.mapper;

import com.ty.pojo.Authorization;
import com.ty.pojo.User;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * @Author:TY
 * @Descroption:
 * @Date: Created in 11:34 2019/8/1
 * @Modificd By:
 */
public interface UserMapper {

    @Select("select * from sys_user")
    List findAll();
    /**
     * 查詢當(dāng)前用戶對象
     */

    public User findByUserName(String username);


    /**
     * 查詢當(dāng)前用戶的權(quán)限
     */
    List findAuthorizationByUserName(String username);

    /**
     * 修改密碼
     */

    @Update("update sys_user set password=#{password} where username=#{username}")
    public void updatePassword(User user);


}

UserMapper.xml:







    


    

想要測試就這樣


在MainController里面添加一個驗證碼接口(生成驗證碼網(wǎng)上都有,這里就不列出了)

    @RequestMapping("/imageCode")
    public void imageCode(HttpServletRequest request, HttpServletResponse response) throws Exception {

//        ImageCodeProcessor.send(new ServletWebRequest(request,response),new ImageCodeGenerator().generate(new ServletWebRequest(request)));
        ImageCode generate = new ImageCodeGenerator().generate(new ServletWebRequest(request));
        HttpSession session = request.getSession();
        System.out.println("生成的驗證碼為:"+generate.getCode());
        session.setAttribute("key",generate.getCode());
        response.setContentType("image/jpeg");
        // 將圖像輸出到Servlet輸出流中。
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(generate.getImage(), "jpeg", sos);
        sos.close();
    }

pojo包中的User對象,里面添加了一個權(quán)限的字段,是user表中沒有的,并且User對象實現(xiàn)了UserDetails接口,實現(xiàn)了其中的方法,方便后面security使用

package com.ty.pojo;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class User implements UserDetails{

  private Integer id;
  private String username;
  private String password;
  private String realname;
  private java.util.Date createDate;
  private java.util.Date lastLoginTime;
  private boolean enabled;
  private boolean accountNonExpired;
  private boolean accountNonLocked;
  private boolean credentialsNonExpired;

  //用戶擁有的所有權(quán)限
  List  authorities=new ArrayList<>();

  @Override
  public String toString() {
    return "User{" +
            "username="" + username + """ +
            ", realname="" + realname + """ +
            ", authorities=" + authorities +
            "}";
  }

  @Override
  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public List getAuthorities() {
    return authorities;
  }



  public void setAuthorities(List authorities) {
    this.authorities = authorities;
  }

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getRealname() {
    return realname;
  }

  public void setRealname(String realname) {
    this.realname = realname;
  }

  public Date getCreateDate() {
    return createDate;
  }

  public void setCreateDate(Date createDate) {
    this.createDate = createDate;
  }

  public Date getLastLoginTime() {
    return lastLoginTime;
  }

  public void setLastLoginTime(Date lastLoginTime) {
    this.lastLoginTime = lastLoginTime;
  }

  public boolean isEnabled() {
    return enabled;
  }

  public void setEnabled(boolean enabled) {
    this.enabled = enabled;
  }

  public boolean isAccountNonExpired() {
    return accountNonExpired;
  }

  public void setAccountNonExpired(boolean accountNonExpired) {
    this.accountNonExpired = accountNonExpired;
  }

  public boolean isAccountNonLocked() {
    return accountNonLocked;
  }

  public void setAccountNonLocked(boolean accountNonLocked) {
    this.accountNonLocked = accountNonLocked;
  }

  public boolean isCredentialsNonExpired() {
    return credentialsNonExpired;
  }

  public void setCredentialsNonExpired(boolean credentialsNonExpired) {
    this.credentialsNonExpired = credentialsNonExpired;
  }
}

其它表就直接用idea自帶的工具:數(shù)據(jù)庫生成pojo類執(zhí)行就行了

連接數(shù)據(jù)庫點擊

springSecurity.xml:里面都有注釋,而且也不難,一看就會系列



    
    
        
        
        
        
        
        

        

        
        



        
        

        


        
        
        

        
        
        
    

    
        
            
            
        
    


    
        
    

    
    

    
    

    


    
    
        
        
        
    

MyUserDetailService :這里就動態(tài)在數(shù)據(jù)庫里面動態(tài)查詢了用戶的權(quán)限,然后因為之前我們的User類實現(xiàn)了UserDetails接口,所以當(dāng)返回我們自己從數(shù)據(jù)庫查詢的用戶然后返回的時候,springSecurity會自己拿著用戶輸入的信息和我們數(shù)據(jù)庫中的做一個比對,對比上了則認(rèn)證成功

package com.ty.security;

import com.ty.mapper.UserMapper;
import com.ty.pojo.Authorization;
import com.ty.pojo.User;
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 java.util.ArrayList;
import java.util.List;

/**
 * @Author:TY
 * @Descroption:
 * @Date: Created in 17:09 2019/8/1
 * @Modificd By:
 */
public class MyUserDetailService implements UserDetailsService{
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user=null;
        System.out.println(username);
        if(username!=null&&!username.equals(""))
        {
              user = userMapper.findByUserName(username);
            if (user!=null)
            {
                //獲取用戶權(quán)限
                List  permList = userMapper.findAuthorizationByUserName(username);
                List authorizations=new ArrayList<>();
                for (Authorization perm:permList)
                {
                     GrantedAuthority authority=new SimpleGrantedAuthority(perm.getAuthorizationMark());
                     authorizations.add(authority);
                }
                user.setAuthorities(authorizations);
            }
            return user;
        }

        return user;
    }

}

然后我們自定義成功后的處理器MySuccessAthenticationHandler

package com.ty.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:TY
 * @Descroption:
 * @Date: Created in 19:43 2019/8/1
 * @Modificd By:
 */
public class MySuccessAthenticationHandler implements AuthenticationSuccessHandler {
    private static final ObjectMapper objectMapper=new ObjectMapper();
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        Map map=new HashMap();
        map.put("success",true);
        String result = objectMapper.writeValueAsString(map);
        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.getWriter().write(result);
    }
}

失敗處理器:

package com.ty.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:TY
 * @Descroption:
 * @Date: Created in 21:23 2019/7/31
 * @Modificd By:
 */
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler{
    private    ObjectMapper objectMapper=new ObjectMapper();
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        Map map=new HashMap();
        map.put("success",false);
        map.put("errorMsg",e.getMessage());
        String result = objectMapper.writeValueAsString(map);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(result);
    }
}

登錄的時候是先驗證驗證碼,驗證碼通過在驗證用戶名和密碼
驗證碼的攔截器

package com.ty.security;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author:TY
 * @Descroption:,他能夠確保在一次請求只通過一次filter,而不需要重復(fù)執(zhí)行
 *
 * @Date: Created in 21:22 2019/8/1
 * @Modificd By:
 */
public class ImageCodeAuthenticationFilter extends OncePerRequestFilter {

    private AuthenticationFailureHandler authenticationFailureHandler;


    public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
        this.authenticationFailureHandler = authenticationFailureHandler;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //判斷當(dāng)前請求,是否為登錄請求,
        if (request.getRequestURI().contains("/login"))
        {
           try {
               //校驗驗證碼
               //表單填的驗證碼
               String imageCode = request.getParameter("imageCode");
               System.out.println("表單填的驗證碼為:"+imageCode);
               //系統(tǒng)生成的驗證碼
               HttpSession session = request.getSession();
               String  sesstionCode = (String) session.getAttribute("key");
               System.out.println("session里的驗證碼為:"+sesstionCode);
               if(imageCode==null||imageCode.equals(""))
               {
                   throw new ImageCodeException("驗證碼不能為空");
               }
               if(!imageCode.equals(sesstionCode))
               {
                   throw new ImageCodeException("驗證碼錯誤");
               }
           }catch (AuthenticationException e){
             //交給自定義的
               authenticationFailureHandler.onAuthenticationFailure(request,response,e);
               return;
           }
        }
        filterChain.doFilter(request,response);
    }
}

驗證碼異常類

package com.ty.security;


import org.springframework.security.core.AuthenticationException;

/**
 * @Author:TY
 * @Descroption:
 * @Date: Created in 21:47 2019/8/1
 * @Modificd By:
 */
public class ImageCodeException extends AuthenticationException {

    public ImageCodeException(String msg, Throwable t) {
        super(msg, t);
    }

    public ImageCodeException(String msg) {
        super(msg);
    }
}

注意:我們是把驗證碼過濾器加在UserNamePasswordAuthenticationFilter前面的,當(dāng)我們的驗證碼拋出異常,驗證碼沒通過時會拋一個ImageCodeException,這個類繼承了AuthenticationException ,所以當(dāng)拋出異常之后會到我們自定義的MyAuthenticationFailureHandler,這樣就可以向前端返回異常的數(shù)據(jù)

login.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: TY
  Date: 2019/7/31
  Time: 19:14
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    登錄頁面



    用戶名或密碼錯誤

用戶名:
密 碼:
驗證碼:
記住我

如果要根據(jù)權(quán)限顯示前端內(nèi)容,就在pom.xml引入

    
      org.springframework.security
      spring-security-taglibs
      4.2.3.RELEASE
    

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: TY
  Date: 2019/7/31
  Time: 16:49
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://www.springframework.org/security/tags" prefix="security" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


    首頁



    歡迎${username}登陸

以下是網(wǎng)站的功能

    商品添加


    商品修改


    商品查詢



    商品刪除


**最后如果想要獲取認(rèn)證通過后的用戶的信息,任何地方都能獲取
可以使用SecurityContextHolder.getContext().getAuthentication().getPrincipal()

    /**
     * 首頁  SecurityContextHolder.getContext().getAuthentication().getPrincipal()可以在任何地方獲取當(dāng)前用戶的信息
     */
    @RequestMapping("index")
    public String index(Model model)
    {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(principal!=null)
        {
            if(principal instanceof UserDetails)
            {
               UserDetails userDetails= (UserDetails)principal;
               model.addAttribute("username",userDetails.getUsername());
            }
        }
        return "index";
    }

**

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/75767.html

相關(guān)文章

  • SpringSecurity系列01】初識SpringSecurity

    摘要:什么是是一個能夠為基于的企業(yè)應(yīng)用系統(tǒng)提供聲明式的安全訪問控制解決方案的安全框架。它來自于,那么它與整合開發(fā)有著天然的優(yōu)勢,目前與對應(yīng)的開源框架還有。通常大家在做一個后臺管理的系統(tǒng)的時候,應(yīng)該采用判斷用戶是否登錄。 ? 什么是SpringSecurity ? ? Spring Security是一個能夠為基于Spring的企業(yè)應(yīng)用系統(tǒng)提供聲明式的安全訪問控制解決方案的安全...

    elva 評論0 收藏0
  • 兩年了,我寫了這些干貨!

    摘要:開公眾號差不多兩年了,有不少原創(chuàng)教程,當(dāng)原創(chuàng)越來越多時,大家搜索起來就很不方便,因此做了一個索引幫助大家快速找到需要的文章系列處理登錄請求前后端分離一使用完美處理權(quán)限問題前后端分離二使用完美處理權(quán)限問題前后端分離三中密碼加鹽與中異常統(tǒng)一處理 開公眾號差不多兩年了,有不少原創(chuàng)教程,當(dāng)原創(chuàng)越來越多時,大家搜索起來就很不方便,因此做了一個索引幫助大家快速找到需要的文章! Spring Boo...

    huayeluoliuhen 評論0 收藏0
  • SpringSecurity01(使用傳統(tǒng)的xml方式開發(fā),且不連接數(shù)據(jù)庫)

    摘要:創(chuàng)建一個工程在里面添加依賴,依賴不要隨便改我改了出錯了好幾次都找不到原因可以輕松的將對象轉(zhuǎn)換成對象和文檔同樣也可以將轉(zhuǎn)換成對象和配置 1.創(chuàng)建一個web工程2.在pom里面添加依賴,依賴不要隨便改,我改了出錯了好幾次都找不到原因 UTF-8 1.7 1.7 2.5.0 1.2 3.0-alpha-1 ...

    Gilbertat 評論0 收藏0
  • Spring4和SpringSecurity4的整合(二)連接mybatis和mysql

    摘要:在上一篇基本配置了一些文件中,基本可以在文件中指定用戶名和密碼來進(jìn)行實現(xiàn)的驗證,這次和一起來配合使用加入的配置文件別名在的中配置數(shù)據(jù)源查找配置事物然后建立層,和層以及對應(yīng)這里省略實 在上一篇基本配置了一些文件中,基本可以在文件中指定用戶名和密碼來進(jìn)行實現(xiàn)SpringSecurity的驗證,這次和mynatis一起來配合使用 加入mybatis的配置文件: mybatis-config....

    NoraXie 評論0 收藏0

發(fā)表評論

0條評論

FrancisSoung

|高級講師

TA的文章

閱讀更多
最新活動
閱讀需要支付1元查看
<