欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring security

程序员文章站 2022-06-19 11:30:30
...
[b]spring security[/b]
security,就是实现了一套用户访问权限的工具(框架),使用者只要完成相关的配置就可以实现权限访问了,不用自己用过滤器来完成一套。
是以userName作为惟一检索用户信息的,


[b]
最简单的security就是用默认的配置[/b]
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>



配置登陆名和密码
#security安全机制
security.user.name=xing
security.user.password=123456


会用浏览器默认的登陆界面,输入帐号密码
帐号密码会以base64方式进行加密后放到HTTP请求中的Headers中的Authorization:


[b]security用自己的配置[/b]
1.如果有登陆页面,进行验证的也会过滤/login,用户名的请求字段 默认为userName,password-parameter 密码的请求字段 默认为password
2.通过session来处理记着登陆状态的


<
?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.midea</groupId>
<artifactId>base</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>base</name>


<!-- 设定仓库,按设定顺序进行查找. -->
<!--<repositories> <repository> <id>public</id> <name>Team Nexus Repository</name>
<url>http://10.33.183.113:8081/nexus/content/groups/public</url> <snapshots>
<enabled>true</enabled> <updatePolicy>always</updatePolicy> </snapshots>
</repository> </repositories> <pluginRepositories> <pluginRepository> <id>public</id>
<name>Team Nexus Repository</name> <url>http://10.33.183.113:8081/nexus/content/groups/public</url>
<snapshots> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </snapshots>
</pluginRepository> </pluginRepositories> -->

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<!-- <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency> -->

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>

</build>
</project>



server.port=8080


#服务器路径
#server.context-path=/eurekaServer

#spring.application.name=securityTest

##gitHub路径
#spring.cloud.config.server.git.uri=https://github.com/huangyongxing310/springCloudConfigTest.git
##文件路径,如果是根目录可以不配置
#spring.cloud.config.server.git.searchPaths=test
##配置仓库的分支,
#spring.cloud.config.label=master
##gitHub帐号密码
#[email protected]
#spring.cloud.config.server.git.password=xing310600

#security安全机制
#security.user.name=xing
#security.user.password=123456

#eureka.client.serviceUrl.defaultZone=http://localhost:8761/eurekaServer/eureka/

# 设置对称**
#encrypt.key=123456



src/main/resources/templates/login.html

<!DOCTYPE html>  
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
用户名或密码错
</div>
<div th:if="${param.logout}">
您已注销成功
</div>
<form th:action="@{/login}" method="post">
<div><label> 用户名 : <input type="text" name="username"/> </label></div>
<div><label> 密 码 : <input type="password" name="password"/> </label></div>
<div><input type="submit" value="登录"/></div>
</form>
</body>
</html>


package com.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;


@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

//配置那些API要进行权限的访问
@Override
protected void configure(HttpSecurity http) throws Exception {
// http
// .authorizeRequests()
// .antMatchers("/", "/home").permitAll()
// .anyRequest().authenticated()
// .and()
// .formLogin()
// .loginPage("/login")
// .permitAll()
// .and()
// .logout()
// .permitAll();


http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}

//进行用户信息认证时会调用这里获取用户的相关信息来与用户发送过来的信息进行比较
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
// auth.inMemoryAuthentication()
// .withUser("user").password("password").roles("USER")
// .and()
// .withUser("app_client").password("nopass").roles("USER")
// .and()
// .withUser("admin").password("password").roles("ADMIN");
//配置用户来源于数据库
auth.userDetailsService(userDetailsService());
}

//这个可以作为扩展,查询数据库里这个用户的相关信息
@Bean
public UserDetailsService userDetailsService() {
return new UserDetailsService() {
@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
// 通过用户名获取用户信息
// Account account = accountRepository.findByName(name);

// if (account != null) {
// 创建spring security安全用户
System.out.println("123456789");
User user = new User("xing", "123456",
AuthorityUtils.createAuthorityList(new String []{"USER"}));
return user;
// } else {
// throw new UsernameNotFoundException("用户[" + name + "]不存在");
// }
}
};

}



/* @Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("xing").password("123456").roles("USER");
}*/

}


package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import io.swagger.annotations.Api;

@Api(value = "/login", description = "测试接口", tags = "LoginController")
@Controller
public class LoginController {
@RequestMapping("/login")
public String login() {
return "login";
}

}


package com.controller;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;

@Api(value = "/Test", description = "测试接口", tags = "TestController")
@RequestMapping("/Test")
@RestController
public class TestController {
final static Logger logger = LogManager.getLogger(TestController.class);

@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test() {
logger.info("test");

return "test";
}
}


package com;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;


@SpringBootApplication //spring boot 开启应用
//@EnableConfigServer //表示开启Config服务
//@EnableEurekaClient //只能为eureka作用
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}



1.打开某个页面,security过滤器检测到这个页面有权限管理就生成一session,保存打开的URL(保证后面跳转回这个页面)。
2.用户输入帐号和密码,security对比系统中的帐号和密码和权限,如果一致就生成一个新和session并跳转回之前的页面。
3.跳转回之前的页面,因为对比到有session了,所以就可以访问这个API了


[b]注销功能[/b]:http://localhost:8080/login?logout


参考:[url]http://www.jianshu.com/p/694d157bb1bc[/url]
参考:[url]http://www.leftso.com/blog/139.html[/url]


http://localhost:8080/Test/test