最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring security基于數(shù)據(jù)庫中賬戶密碼認(rèn)證

 更新時(shí)間:2020年03月09日 12:38:12   作者:程序曉猿  
這篇文章主要介紹了Spring security基于數(shù)據(jù)庫中賬戶密碼認(rèn)證,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

一、原理分析

前臺(tái)的登錄請(qǐng)求發(fā)送到后端后會(huì)由spring security進(jìn)行攔截,即controller層由框架自己提供。這樣用戶名和密碼的認(rèn)證就需要在service層完成,所以框架需要在service層獲取到我們自己的數(shù)據(jù)庫賬號(hào)信息。

spring security 提供了一個(gè)接口 UserDetailsService 來讓用戶提供賬號(hào)和密碼,其內(nèi)容如下

public interface UserDetailsService {
  UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}

用戶實(shí)現(xiàn)這個(gè)接口中的loadUserByUsername方法,通過數(shù)據(jù)庫中查詢的賬號(hào)和密碼構(gòu)造一個(gè)UserDetails對(duì)象返回給spring security,然后框架自己完成認(rèn)證操作。

其中UserDetails也是一個(gè)接口,spring security用它來封裝當(dāng)前進(jìn)行認(rèn)證的用戶信息

public interface UserDetails extends Serializable {
  Collection<? extends GrantedAuthority> getAuthorities();
  String getPassword();
  String getUsername();
  boolean isAccountNonExpired();
  boolean isAccountNonLocked();
  boolean isCredentialsNonExpired();
  boolean isEnabled();
}

spring security 自己提供了一個(gè)實(shí)現(xiàn)類我們可以直接使用,以下是User中的部分代碼

public class User implements UserDetails, CredentialsContainer {
private String password;
private final String username;
private final Set<GrantedAuthority> authorities;
private final boolean accountNonExpired; //帳戶是否過期
private final boolean accountNonLocked; //帳戶是否鎖定
private final boolean credentialsNonExpired; //認(rèn)證是否過期
private final boolean enabled; //帳戶是否可用
}

所以,使用數(shù)據(jù)庫完成認(rèn)證的關(guān)鍵就是實(shí)現(xiàn)UserDetailsService接口,并在loadUserByUsername方法中封裝一個(gè)框架需要的UserDetails對(duì)象,即User對(duì)象返回給框架,由框架完成后續(xù)的認(rèn)證操作。

同時(shí)需要在spring security的配置文件中指定要用來認(rèn)證的userService 的bean

二、代碼實(shí)現(xiàn)

1.新建一個(gè)javaWeb工程

新建一個(gè)javaweb工程,導(dǎo)入相關(guān)依賴,pom文件的內(nèi)容如下

pom文件

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>com.lyy</groupId>
 <artifactId>spring_security_1</artifactId>
 <version>1.0-SNAPSHOT</version>
 <packaging>war</packaging>

 <name>spring_security_1 Maven Webapp</name>
 <!-- FIXME change it to the project's website -->
 <url>http://www.example.com</url>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <spring.version>5.0.2.RELEASE</spring.version>
  <slf4j.version>1.6.6</slf4j.version>
  <log4j.version>1.2.12</log4j.version>
  <mysql.version>5.1.6</mysql.version>
  <mybatis.version>3.4.5</mybatis.version>
  <spring.security.version>5.0.1.RELEASE</spring.security.version>
 </properties>

 <dependencies>
  <dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjweaver</artifactId>
   <version>1.6.8</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-aop</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context-support</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-orm</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-beans</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-test</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>

  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-tx</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.12</version>
   <scope>test</scope>
  </dependency>

  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet.jsp</groupId>
   <artifactId>jsp-api</artifactId>
   <version>2.0</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>jstl</groupId>
   <artifactId>jstl</artifactId>
   <version>1.2</version>
  </dependency>    <!-- log start -->
  <dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
   <version>${log4j.version}</version>
  </dependency>
  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-api</artifactId>
   <version>${slf4j.version}</version>
  </dependency>
  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-log4j12</artifactId>
   <version>${slf4j.version}</version>
  </dependency>    <!-- log end -->

  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>${mysql.version}</version>
  </dependency>

  <dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis</artifactId>
   <version>${mybatis.version}</version>
  </dependency>
  <dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis-spring</artifactId>
   <version>1.3.0</version>
  </dependency>
  <dependency>
   <groupId>c3p0</groupId>
   <artifactId>c3p0</artifactId>
   <version>0.9.1.2</version>
   <type>jar</type>
   <scope>compile</scope>
  </dependency>
  <dependency>
   <groupId>com.github.pagehelper</groupId>
   <artifactId>pagehelper</artifactId>
   <version>5.1.2</version>
  </dependency>
  <dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-web</artifactId>
   <version>${spring.security.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-config</artifactId>
   <version>${spring.security.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-core</artifactId>
   <version>${spring.security.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-taglibs</artifactId>
   <version>${spring.security.version}</version>
  </dependency>


  <dependency>
   <groupId>javax.annotation</groupId>
   <artifactId>jsr250-api</artifactId>
   <version>1.0</version>
  </dependency>

  <dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.9.7</version>
  </dependency>

  <dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-core</artifactId>
   <version>2.9.7</version>
  </dependency>
  <dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <version>1.16.16</version>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.apache.tomcat.maven</groupId>
     <artifactId>tomcat7-maven-plugin</artifactId>
      <version>2.1</version>
       <configuration>
        <port>80</port>
        <path>/</path>
        <uriEncoding>UTF-8</uriEncoding>
        <server>tomcat7</server>
       </configuration>
   </plugin>

  </plugins>
 </build>
</project>

在web.xml中配置spring security的過濾器

web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
           http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
     version="3.0">

  <display-name>spring security 01</display-name>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-security.xml,classpath*:applicationContext.xml</param-value>
  </context-param>

  <!-- 配置監(jiān)聽器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <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>

  <!-- 解決中文亂碼過濾器 -->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

整合spring和mybatis,spring的配置文件applicationContext.xml

spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop.xsd
  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx.xsd">

  <!-- 開啟注解掃描,管理service和dao -->
  <context:component-scan base-package="com.lyy.service">
  </context:component-scan>
  <context:component-scan base-package="com.lyy.dao">

  </context:component-scan>

  <context:property-placeholder location="classpath:db.properties"/>
  <!-- 配置連接池 -->
  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="${jdbc.driver}"/>
    <property name="jdbcUrl" value="${jdbc.url}"/>
    <property name="user" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
  </bean>

  <!--配置SqlSessionFactory工廠-->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="typeAliasesPackage" value="com.lyy.domain"/>
  </bean>

  <!--配置Dao接口所在包-->
  <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.lyy.dao"/>
  </bean>

  <!-- 配置Spring的聲明式事務(wù)管理 -->
  <!-- 配置事務(wù)管理器 -->
  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
  </bean>

  <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

spring security配置文件

spring security的配置文件的內(nèi)容,spring-security.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security"
    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.xsd
     http://www.springframework.org/schema/security
     http://www.springframework.org/schema/security/spring-security.xsd">

  <!--spring-security的入門配置-->

  <!--配置哪些資源不會(huì)被攔截 /xxx表示根路徑下的某個(gè)資源-->
  <security:http security="none" pattern="/login.html"/>
  <security:http security="none" pattern="/failed.html"/>

  <security:http auto-config="true" use-expressions="false">
    <!-- 配置鏈接地址,表示任意路徑都需要ROLE_USER權(quán)限,這里可以配置
     一個(gè)逗號(hào)隔開的角色列表-->
    <security:intercept-url pattern="/**" access="ROLE_USER"/>

    <!--自定義登錄頁面-->
    <security:form-login login-page="/login.html" login-processing-url="/login"
               username-parameter="username" password-parameter="password"
               authentication-failure-forward-url="/failed.html"
               default-target-url="/index.html"

    />
    <!--關(guān)閉csrf,默認(rèn)是開啟的-->
    <security:csrf disabled="true"/>

    <!-- 退出 -->
    <security:logout invalidate-session="true" logout-url="/logout.do" logout-success-url="/login.html" />
  </security:http>
  <security:authentication-manager>
    <!--配置使用給定的userservice完成認(rèn)證-->
    <security:authentication-provider user-service-ref="userService">
    </security:authentication-provider>
  </security:authentication-manager>
</beans>

在這個(gè)配置文件中要注意的是配置用來認(rèn)證的userService Bean

<!--配置使用給定的userservice完成認(rèn)證-->
<security:authentication-provider user-service-ref="userService">

創(chuàng)建登錄頁面和登錄失敗的頁面login.html,failed.html

2.用戶認(rèn)證的實(shí)現(xiàn)

新建一個(gè)IUserService接口繼承UserDetailsService

package com.lyy.service;
import org.springframework.security.core.userdetails.UserDetailsService;
public interface IUserService extends UserDetailsService {
}

實(shí)現(xiàn)類如下

@Service("userService")
public class UserServiceImpl implements IUserService {

  @Autowired
  private IUserDao userDao;

  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    UserInfo userInfo = userDao.findByUsername(username);
    User user=new User(userInfo.getUsername(),"{noop}"+userInfo.getPassword(),getRoles());
    return user;
  }
  /*給用戶賦值角色信息*/
  private List<SimpleGrantedAuthority> getRoles(){
    List<SimpleGrantedAuthority> list=new ArrayList<SimpleGrantedAuthority>();
    list.add(new SimpleGrantedAuthority("ROLE_USER"));
    list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
    return list;
  }
}

其中在loadUserByUsername方法中完成查詢數(shù)據(jù)庫信息,封裝成框架需要的用戶信息。

注意 :

UserInfo是封裝數(shù)據(jù)庫用戶信息的實(shí)體類

getRoles用來給用戶賦角色信息,spring security認(rèn)證時(shí)用戶必須有角色信息,角色信息可以從數(shù)據(jù)庫中查詢,在這里直接在代理中寫固定值來示意。

用戶密碼中拼接的"{noop}"字符串是因?yàn)槲覀儧]有對(duì)密碼進(jìn)行加密,所以要告訴框架認(rèn)證密碼時(shí)不需要加密。

3.測(cè)試

啟動(dòng)工程,訪問localhost,會(huì)跳轉(zhuǎn)到登錄頁面,輸入數(shù)據(jù)庫中存在的賬戶和密碼就會(huì)登錄成功并跳轉(zhuǎn)到首頁index.html

三、總結(jié)

使用數(shù)據(jù)庫完成認(rèn)證的關(guān)鍵就是實(shí)現(xiàn)UserDetailsService接口,并在loadUserByUsername方法中封裝一個(gè)框架需要的UserDetails對(duì)象,即User對(duì)象返回給框架,由框架完成后續(xù)的認(rèn)證操作。

同時(shí)需要在spring security的配置文件中指定要用來認(rèn)證的userService 的bean,即實(shí)現(xiàn)了loadUserByUsername方法的userService

如果需要查看示例工程的具體代碼,可以點(diǎn)擊下方的鏈接在碼云上查看

示例工程地址

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Pulsar源碼徹底解決重復(fù)消費(fèi)問題

    Pulsar源碼徹底解決重復(fù)消費(fèi)問題

    這篇文章主要為大家介紹了Pulsar源碼徹底解決重復(fù)消費(fèi)問題,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-05-05
  • Java中使用Preconditions來檢查傳入?yún)?shù)介紹

    Java中使用Preconditions來檢查傳入?yún)?shù)介紹

    這篇文章主要介紹了Java中使用Preconditions來檢查傳入?yún)?shù)介紹,本文只是作為一個(gè)簡(jiǎn)單的用法介紹,需要的朋友可以參考下
    2015-06-06
  • SpringBoot設(shè)置首頁(默認(rèn)頁)跳轉(zhuǎn)功能的實(shí)現(xiàn)方案

    SpringBoot設(shè)置首頁(默認(rèn)頁)跳轉(zhuǎn)功能的實(shí)現(xiàn)方案

    這篇文章主要介紹了SpringBoot設(shè)置首頁(默認(rèn)頁)跳轉(zhuǎn)功能,本文通過兩種方案,給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-07-07
  • 詳解springboot集成websocket的兩種實(shí)現(xiàn)方式

    詳解springboot集成websocket的兩種實(shí)現(xiàn)方式

    這篇文章主要介紹了springboot集成websocket的兩種實(shí)現(xiàn)方式,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-01-01
  • Springboot整合GateWay+Nacos實(shí)現(xiàn)動(dòng)態(tài)路由

    Springboot整合GateWay+Nacos實(shí)現(xiàn)動(dòng)態(tài)路由

    本文主要介紹了Springboot整合GateWay+Nacos實(shí)現(xiàn)動(dòng)態(tài)路由,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-08-08
  • SpringBoot項(xiàng)目在IntelliJ IDEA中如何實(shí)現(xiàn)熱部署

    SpringBoot項(xiàng)目在IntelliJ IDEA中如何實(shí)現(xiàn)熱部署

    spring-boot-devtools是一個(gè)為開發(fā)者服務(wù)的一個(gè)模塊,其中最重要的功能就是自動(dòng)應(yīng)用代碼更改到最新的App上面去。,這篇文章主要介紹了SpringBoot項(xiàng)目在IntelliJ IDEA中如何實(shí)現(xiàn)熱部署,感興趣的小伙伴們可以參考一下
    2018-07-07
  • Java數(shù)據(jù)結(jié)構(gòu)之平衡二叉樹的實(shí)現(xiàn)詳解

    Java數(shù)據(jù)結(jié)構(gòu)之平衡二叉樹的實(shí)現(xiàn)詳解

    平衡二叉樹又被稱為AVL樹(有別于AVL算法),且具有以下性質(zhì):它是一棵空樹或它的左右兩個(gè)子樹的高度差的絕對(duì)值不超過1,并且左右兩個(gè)子樹都是一棵平衡二叉樹。本文將詳解介紹一下平衡二叉樹的原理與實(shí)現(xiàn),需要的可以參考一下
    2022-03-03
  • SpringBoot+kaptcha實(shí)現(xiàn)圖片驗(yàn)證碼功能詳解

    SpringBoot+kaptcha實(shí)現(xiàn)圖片驗(yàn)證碼功能詳解

    這篇文章主要為大家詳細(xì)介紹了SpringBoot如何結(jié)合kaptcha實(shí)現(xiàn)圖片驗(yàn)證碼功能,文中的示例代碼講解詳細(xì),有需要的小伙伴可以參考一下
    2024-01-01
  • idea使用帶provide修飾依賴導(dǎo)致ClassNotFound

    idea使用帶provide修飾依賴導(dǎo)致ClassNotFound

    程序打包到Linux上運(yùn)行時(shí),若Linux上也有這些依賴,為了在Linux上運(yùn)行時(shí)避免依賴沖突,可以使用provide修飾,本文主要介紹了idea使用帶provide修飾依賴導(dǎo)致ClassNotFound,下面就來介紹一下解決方法,感興趣的可以了解一下
    2024-01-01
  • 詳解Java的繼承

    詳解Java的繼承

    大家好,本篇文章主要講的是詳解Java的繼承,感興趣的同學(xué)趕快來看一看吧,對(duì)你有幫助的話記得收藏一下,方便下次瀏覽
    2022-01-01

最新評(píng)論

牙克石市| 嘉义市| 玛曲县| 庆城县| 保靖县| 徐水县| 彰武县| 新野县| 琼海市| 和田县| 丹寨县| 遂宁市| 望江县| 延吉市| 肃北| 丹东市| 墨脱县| 岢岚县| 双鸭山市| 博客| 桓仁| 林芝县| 宁晋县| 寿光市| 格尔木市| 沙雅县| 辽宁省| 霸州市| 托克逊县| 万年县| 都安| 扶沟县| 彝良县| 五指山市| 泗洪县| 益阳市| 门头沟区| 凉城县| 贵州省| 易门县| 永善县|