Spring Security(1) 如何使用Java方式进行配置

本文档介绍了如何使用Java配置方式在Spring Boot项目中实现Spring Security的角色认证和权限控制。通过创建名为SpringSecurityDemo的简单项目,展示了MVC配置、Spring Security配置、全局配置以及视图页面的设置。在配置完成后,当访问未授权资源时,系统会自动跳转到登录页面。用户登录后,具备USER角色权限的账号能够成功访问受限页面。
摘要由CSDN通过智能技术生成

根据spring官网关于spring security的参考文档:

https://docs.spring.io/spring-security/site/docs/5.2.2.BUILD-SNAPSHOT/reference/htmlsingle/#hello-spring-security

总共有三种使用security的方式,spring boot, Java配置, xml配置。
本章介绍的是使用Java配置的方式创建一个简单的spring boot项目来进行角色认证和权限控制。

项目名:SpringSecurityDemo
管理工具:maven 3.x
JDK版本:1.8
一. 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.2.0.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>org.roy</groupId>
	<artifactId>SpringSecurityDemo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringSecurityDemo</name>
	<description>Demo project for Spring Security</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
	    <!-- web -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- view -->
	    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-- test -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<!-- Spring security -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

二. 目录结构

在这里插入图片描述
三. 配置文件(使用Java方法)

  1. MVC配置
    MVCConfig.java
package org.roy.Config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MVCConfig implements WebMvcConfigurer{

	public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
        registry.addViewController("/").setViewName("home");
        registry.addViewController("/hello").setViewName("hello");
        registry.addViewController("/login").setViewName("login");
    }
	
}

  1. Spring Security配置

WebSecurityConfig.java

package org.roy.Config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

	@Override
    protected void configure(HttpSecurity http) throws Exception {
		http
		    .authorizeRequests()
		        .antMatchers("/", "/home").permitAll()
		        .anyRequest().authenticated()
		        .and()
		    .formLogin()
		        .loginPage("/login")
		        .permitAll()
		        .and()
		    .logout()
		        .permitAll();
	}
	
	@Bean
	@Override
	public UserDetailsService userDetailsService() {
		UserDetails user =
	        User.withDefaultPasswordEncoder()
	            .username("user")
	            .password("password")
	            .roles("USER")
	            .build();

	        return new InMemoryUserDetailsManager(user);
	}
	
}

  1. global全局配置
    application.properties只配置了端口, 不贴出来了 : )

四. View视图页面

  1. hello.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
    <h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
        <form th:action="@{/logout}" method="post">
        <input type="submit" value="Sign Out"/>
        </form>

</body>
</html>
  1. home.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Welcome</title>
</head>
<body>
<h1><b>Welcome to Spring Security Home Page</b></h1>
<h2>click <a th:href="@{/hello}">here</a> to see hello world</h2>
</body>
</html>
  1. login.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
      xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head>
        <title>Spring Security Example </title>
    </head>
    <body>
        <div th:if="${param.error}">
            Invalid username and password.
        </div>
        <div th:if="${param.logout}">
            You have been logged out.
        </div>
        <form th:action="@{/login}" method="post">
            <div><label> User Name : <input type="text" name="username"/> </label></div>
            <div><label> Password: <input type="password" name="password"/> </label></div>
            <div><input type="submit" value="Sign In"/></div>
        </form>
    </body>
</html>

五. 启动类

SpringSecurityDemoApplication.java

package org.roy.springsecurityDemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@ComponentScan(basePackages = {"org.roy.springsecurityController","org.roy.Config"})
public class SpringSecurityDemoApplication {


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

}

首先运行main方法, 然后打开浏览器

  1. 访问http://localhost:8082/home
    home页面没有被拦截
    在这里插入图片描述
    因为在spring security配置了:
http
		    .authorizeRequests()
		        .antMatchers("/", "/home").permitAll()
		        .anyRequest().authenticated()

也就是说该请求被放过了,那么如果访问没有进行配置的资源会怎么样呢?点击“here”,指向了“/hello”资源,不过hello是没有进行任何配置的.
在这里插入图片描述
结果显示跳到了login页面,这个是spring security的默认设置,自动转到配置好的login页面(即使没有实现自己的login页面,security也会使用自带的默认登陆界面)。于是输入用户名密码,提交后:
在这里插入图片描述
因为该账号拥有USER角色的权限, 所以可以成功访问到hello界面。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值