中文亚洲精品无码_熟女乱子伦免费_人人超碰人人爱国产_亚洲熟妇女综合网

當(dāng)前位置: 首頁 > news >正文

網(wǎng)絡(luò)規(guī)劃設(shè)計師屬于高級職稱嗎北京網(wǎng)站優(yōu)化指導(dǎo)

網(wǎng)絡(luò)規(guī)劃設(shè)計師屬于高級職稱嗎,北京網(wǎng)站優(yōu)化指導(dǎo),哪個網(wǎng)站可以做excel,網(wǎng)頁設(shè)計尺寸單位Spring Security是Spring官方推薦的認(rèn)證、授權(quán)框架,功能相比Apache Shiro功能更豐富也更強(qiáng)大,但是使用起來更麻煩。 如果使用過Apache Shiro,學(xué)習(xí)Spring Security會比較簡單一點(diǎn),兩種框架有很多相似的地方。 目錄 一、準(zhǔn)備工作 …

Spring Security是Spring官方推薦的認(rèn)證、授權(quán)框架,功能相比Apache Shiro功能更豐富也更強(qiáng)大,但是使用起來更麻煩。

如果使用過Apache Shiro,學(xué)習(xí)Spring Security會比較簡單一點(diǎn),兩種框架有很多相似的地方。

目錄

一、準(zhǔn)備工作

創(chuàng)建springboot項(xiàng)目

pom.xml

application.yml

二、創(chuàng)建相關(guān)的類

UserDetailsService

SecurityConfig.java

SystemProperties.java

MybatisPlusConfig.java

三、完成登錄接口

創(chuàng)建數(shù)據(jù)庫實(shí)體類

創(chuàng)建持久層接口

創(chuàng)建登錄DTO對象

創(chuàng)建控制器類

創(chuàng)建業(yè)務(wù)層類

自定義登錄成功處理器


一、準(zhǔn)備工作

創(chuàng)建springboot項(xiàng)目

首先,通過IntelliJ IDEA創(chuàng)建一個springboot項(xiàng)目,項(xiàng)目名為springboot-springsecurity,在pom.xml中添加相關(guān)依賴。

pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.4.RELEASE</version><relativePath /></parent><groupId>com.example</groupId><artifactId>springboot-springsecurity</artifactId><version>0.0.1-SNAPSHOT</version><properties><java.version>1.8</java.version><jjwt.version>0.9.1</jjwt.version><mysql.version>8.0.28</mysql.version><druid.version>1.1.21</druid.version><lombok.version>1.18.22</lombok.version><mybatis.version>2.2.2</mybatis.version><mybatis-plus.version>3.5.1</mybatis-plus.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--validation--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency><!--spring security--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><!--mysql--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql.version}</version></dependency><!--druid--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>${druid.version}</version></dependency><!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>${lombok.version}</version></dependency><!--mybatis--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>${mybatis.version}</version></dependency><!--mybatis-plus--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>${mybatis-plus.version}</version></dependency><!--jjwt--><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>${jjwt.version}</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>

application.yml

server:port: 8080servlet:context-path: /spring:datasource:username: rootpassword: rooturl: jdbc:mysql://localhost:3306/spring_securitydriver-class-name: com.mysql.cj.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSourcemybatis-plus:mapper-locations: classpath:mapper/*Mapper.xmllogging:level:springfox: errorcom.example.security: debugsystem:login-page: /login.htmllogin-url: /user/loginindex-page: /index.htmllogout-url: /user/logoutparameter:username: usernamepassword: passwordwhite-url:- /js/**- /css/**- /images/**- /user/login- /login.html

二、創(chuàng)建相關(guān)的類

UserDetailsService

UserDetailsService接口是Spring Security中非常重要的接口,在登錄認(rèn)證的時候會通過這個接口的loadUserByUsername()方法獲取用戶的信息,來完成登錄的用戶名、密碼校驗(yàn),完成登錄流程。

我們需要創(chuàng)建一個UserDetailsService的實(shí)現(xiàn)類,并聲明為Spring組件。

package com.example.security.security;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.security.entity.User;
import com.example.security.exception.GlobalException;
import com.example.security.mapper.UserMapper;
import com.example.security.restful.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
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.Component;import java.util.ArrayList;
import java.util.List;/*** @author heyunlin* @version 1.0*/
@Component
public class UserDetailsServiceImpl implements UserDetailsService {private final UserMapper userMapper;@Autowiredpublic UserDetailsServiceImpl(UserMapper userMapper) {this.userMapper = userMapper;}@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {// 查詢用戶信息User user = selectByUsername(username);if (user == null) {throw new BadCredentialsException("登錄失敗,用戶名不存在!");} else {List<String> permissions = selectPermissions(username);return org.springframework.security.core.userdetails.User.builder().username(user.getUsername()).password(user.getPassword()).accountExpired(false).accountLocked(false).disabled(!user.getEnable()).credentialsExpired(false).authorities(permissions.toArray(new String[] {})).build();}}/*** 通過用戶名查詢用戶信息* @param username 用戶名* @return User*/private User selectByUsername(String username) {QueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.eq("username", username);List<User> list = userMapper.selectList(wrapper);if (list.size() == 1) {return list.get(0);}return null;}/*** 通過用戶名查詢用戶權(quán)限* @param username 用戶名* @return List<String>*/private List<String> selectPermissions(String username) {if (username == null) {throw new GlobalException(ResponseCode.BAD_REQUEST, "用戶名不能為空");}List<String> permissions = new ArrayList<>();permissions.add("/user/login");permissions.add("/user/logout");permissions.add("/user/selectById");return permissions;}}

SecurityConfig.java

創(chuàng)建security的配置類

package com.example.security.config;import com.example.security.security.LoginFailHandler;
import com.example.security.security.LoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;/*** @author heyunlin* @version 1.0*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {private final SystemProperties systemProperties;@Autowiredpublic SecurityConfig(SystemProperties systemProperties) {this.systemProperties = systemProperties;}@Beanpublic PasswordEncoder passwordEncoder() {return new PasswordEncoder() {@Overridepublic String encode(CharSequence charSequence) {return (String) charSequence;}@Overridepublic boolean matches(CharSequence charSequence, String s) {return charSequence.equals(s);}};}@Bean@Overridepublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}@Overrideprotected void configure(HttpSecurity http) throws Exception {// 禁用防跨域攻擊http.csrf().disable();// 配置各請求路徑的認(rèn)證與授權(quán)http.formLogin().loginPage(systemProperties.getLoginPage()) // 自定義登錄頁面的地址.loginProcessingUrl(systemProperties.getLoginUrl()) // 處理登錄的接口地址.usernameParameter(systemProperties.getParameter().get("username")) // 用戶名的參數(shù)名.passwordParameter(systemProperties.getParameter().get("password")) // 密碼的參數(shù)名.successHandler(new LoginSuccessHandler(systemProperties))//.successForwardUrl("/index.html") // 登錄成功跳轉(zhuǎn)的地址.failureHandler(new LoginFailHandler()); // 登錄失敗的處理器// 退出登錄相關(guān)配置http.logout().logoutUrl(systemProperties.getLogoutUrl()) // 退出登錄的接口地址.logoutSuccessUrl(systemProperties.getLoginUrl()); // 退出登錄成功跳轉(zhuǎn)的地址// 配置認(rèn)證規(guī)則String[] toArray = systemProperties.getWhiteUrl().toArray(new String[]{});http.authorizeRequests().antMatchers(toArray).permitAll() // 白名單,也就是不需要登錄也能訪問的資源.anyRequest().authenticated();}}

SystemProperties.java

package com.example.security.config;import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;import java.util.List;
import java.util.Map;/*** @author heyunlin* @version 1.0*/
@Data
@Component
@ConfigurationProperties(prefix = "system")
public class SystemProperties {/*** 登錄頁面*/private String loginPage;/*** 登錄的請求地址*/private String loginUrl;/*** 登錄成功后跳轉(zhuǎn)的頁面*/private String indexPage;/*** 退出登錄的請求地址*/private String logoutUrl;/*** 白名單*/private List<String> whiteUrl;/*** 登錄的參數(shù)*/private Map<String, String> parameter;
}

MybatisPlusConfig.java

package com.example.security.config;import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** @author heyunlin* @version 1.0*/
@Configuration
@MapperScan(basePackages = "com.example.security.mapper")
public class MybatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();// 防全表更新與刪除插件interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());// 分頁插件interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}}

三、完成登錄接口

創(chuàng)建數(shù)據(jù)庫實(shí)體類

User.java

package com.example.security.entity;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;import java.io.Serializable;
import java.time.LocalDateTime;/*** 用戶* @author heyunlin* @version 1.0*/
@Data
@TableName("user")
public class User implements Serializable {private static final long serialVersionUID = 18L;@TableId(value = "id", type = IdType.INPUT)private String id;/*** 姓名*/private String name;/*** 性別*/private Integer gender;/*** 用戶名*/private String username;/*** 密碼*/private String password;/*** 手機(jī)號*/private String phone;/*** 是否啟用*/private Boolean enable;/*** 最后一次登錄時間*/@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")private LocalDateTime lastLoginTime;
}

創(chuàng)建持久層接口

package com.example.security.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.security.entity.User;
import org.springframework.stereotype.Repository;/*** @author heyunlin* @version 1.0*/
@Repository
public interface UserMapper extends BaseMapper<User> {}

創(chuàng)建登錄DTO對象

package com.example.security.dto;import lombok.Data;import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.Serializable;/*** @author heyunlin* @version 1.0*/
@Data
public class UserLoginDTO implements Serializable {private static final long serialVersionUID = 18L;/*** 用戶名*/@NotNull(message = "用戶名不允許為空")@NotEmpty(message = "用戶名不允許為空")private String username;/*** 密碼*/@NotNull(message = "密碼不允許為空")@NotEmpty(message = "密碼不允許為空")private String password;
}

創(chuàng)建控制器類

package com.example.security.controller;import com.example.security.dto.UserLoginDTO;
import com.example.security.entity.User;
import com.example.security.restful.JsonResult;
import com.example.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;/*** @author heyunlin* @version 1.0*/
@RestController
@RequestMapping(path = "/user", produces = "application/json;charset=utf-8")
public class UserController {private final UserService userService;@Autowiredpublic UserController(UserService userService) {this.userService = userService;}@RequestMapping(value = "/login", method = RequestMethod.POST)public JsonResult<Void> login(@Validated UserLoginDTO userLoginDTO) {userService.login(userLoginDTO);return JsonResult.success("登錄成功");}@RequestMapping(value = "/logout", method = RequestMethod.POST)public JsonResult<Void> logout() {userService.logout();return JsonResult.success("登出成功");}@RequestMapping(value = "/selectById", method = RequestMethod.GET)public JsonResult<User> selectById(@RequestParam(value = "id", required = true) String userId) {User user = userService.selectById(userId);return JsonResult.success(null, user);}}

創(chuàng)建業(yè)務(wù)層類

UserService接口

package com.example.security.service;import com.example.security.dto.UserLoginDTO;
import com.example.security.entity.User;/*** @author heyunlin* @version 1.0*/
public interface UserService {/*** 登錄認(rèn)證* @param userLoginDTO 用戶登錄信息*/void login(UserLoginDTO userLoginDTO);/*** 退出登錄*/void logout();/*** 通過ID查詢用戶信息* @param userId 用戶ID* @return User 通過ID查詢到的用戶信息*/User selectById(String userId);
}

UserServiceImpl.java

package com.example.security.service.impl;import com.example.security.dto.UserLoginDTO;
import com.example.security.entity.User;
import com.example.security.mapper.UserMapper;
import com.example.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;/*** @author heyunlin* @version 1.0*/
@Service
public class UserServiceImpl implements UserService {private final UserMapper userMapper;private final AuthenticationManager authenticationManager;@Autowiredpublic UserServiceImpl(UserMapper userMapper, AuthenticationManager authenticationManager) {this.userMapper = userMapper;this.authenticationManager = authenticationManager;}@Overridepublic void login(UserLoginDTO userLoginDTO) {Authentication authentication = new UsernamePasswordAuthenticationToken(userLoginDTO.getUsername(),userLoginDTO.getPassword());authenticationManager.authenticate(authentication);}@Overridepublic void logout() {// todo}@Overridepublic User selectById(String userId) {return userMapper.selectById(userId);}}

自定義登錄成功處理器

登陸成功直接重定向到/index.html

package com.example.security.security;import com.example.security.config.SystemProperties;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;/*** @author heyunlin* @version 1.0*/
public class LoginSuccessHandler implements AuthenticationSuccessHandler {private final SystemProperties systemProperties;public LoginSuccessHandler(SystemProperties systemProperties) {this.systemProperties = systemProperties;}@Overridepublic void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {response.sendRedirect(systemProperties.getIndexPage());}}

至此,springboot整合Spring Security就完成了,項(xiàng)目結(jié)構(gòu)如下。

文章就分享到這里了,代碼已開源,可按需獲取~

springboot整合spring securityicon-default.png?t=N7T8https://gitee.com/he-yunlin/springboot-springsecurity.git

http://www.risenshineclean.com/news/35413.html

相關(guān)文章:

  • 如何做全景素材網(wǎng)站網(wǎng)絡(luò)營銷的幾種模式
  • 深圳電子商務(wù)網(wǎng)站建設(shè)百度關(guān)鍵詞優(yōu)化快速排名軟件
  • 淘金企業(yè)網(wǎng)站建設(shè)紹興seo排名外包
  • 房價走勢最新消息2022aso優(yōu)化運(yùn)營
  • 公司做網(wǎng)站的費(fèi)用怎么做賬百度權(quán)重劃分等級
  • 網(wǎng)站模版保護(hù)域名跳轉(zhuǎn)長沙seo優(yōu)化服務(wù)
  • 黃頁網(wǎng)站大全通俗易懂免費(fèi)域名注冊永久
  • 展覽公司網(wǎng)站建設(shè)方案百度seo可能消失
  • 免費(fèi)建立平臺網(wǎng)站關(guān)系營銷案例
  • 北京企業(yè)網(wǎng)站設(shè)計公司自己建網(wǎng)站要多少錢
  • 洛陽做多屏合一網(wǎng)站公司廣告推廣方案
  • 佛山做網(wǎng)站制作公司長沙seo霸屏
  • 為什么選擇當(dāng)網(wǎng)站設(shè)計人員怎么做電商賣東西
  • 莘縣建設(shè)局網(wǎng)站鏈接搜索
  • 商業(yè)網(wǎng)站圖片百度聯(lián)系電話
  • 網(wǎng)站建設(shè)手機(jī)端官網(wǎng)網(wǎng)站關(guān)鍵詞優(yōu)化排名推薦
  • 男性網(wǎng)站推廣方法品牌營銷策劃書
  • 云南專業(yè)做網(wǎng)站多少錢北京網(wǎng)站優(yōu)化常識
  • 做招聘和求職都需要哪些網(wǎng)站最近五天的新聞大事
  • 做外貿(mào)網(wǎng)站客服注冊推廣
  • 網(wǎng)站開發(fā)工資產(chǎn)品設(shè)計公司
  • 怎么用ftp上傳網(wǎng)站seo建站
  • 五八同城找工作紹興百度seo
  • wordpress 經(jīng)過天數(shù)大地seo視頻
  • 注冊空殼公司判幾年網(wǎng)站搜索優(yōu)化官網(wǎng)
  • 免費(fèi)做網(wǎng)站的平臺網(wǎng)站排名查詢工具有哪些
  • 電子商城網(wǎng)站設(shè)計論文seo指的是什么意思
  • 專業(yè)做網(wǎng)站建設(shè)公司福州seo網(wǎng)絡(luò)推廣
  • 浙江新華建設(shè)有限公司官方網(wǎng)站站長seo查詢
  • 收藏的網(wǎng)站從做系統(tǒng)后找不到了東莞關(guān)鍵詞優(yōu)化推廣