springsecurity入门案例

没有引用Spring Security依赖,是不会出现访问接口需要登录。只要引入了Spring Security依赖,Spring Boot就会对Spring Security做进行默认的权限管理配置,默认情况下,它要求所有的请求必须认证后才能访问

第一步:创建springboot项目

springsecurity入门案例_第1张图片

第二步:pom.xml


<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.0modelVersion>
	<parent>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starter-parentartifactId>
		<version>2.2.1.RELEASEversion>
		<relativePath/> 
	parent>
	<groupId>com.springbootgroupId>
	<artifactId>security-demo01-startartifactId>
	<version>0.0.1-SNAPSHOTversion>
	<name>security-demo01-startname>
	<description>Demo project for Spring Bootdescription>
	<properties>
		<java.version>1.8java.version>
	properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-securityartifactId>
		dependency>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-webartifactId>
		dependency>

		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-testartifactId>
			<scope>testscope>
		dependency>
		<dependency>
			<groupId>org.springframework.securitygroupId>
			<artifactId>spring-security-testartifactId>
			<scope>testscope>
		dependency>
	dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.bootgroupId>
				<artifactId>spring-boot-maven-pluginartifactId>
			plugin>
		plugins>
	build>

project>

第三步:application.properties

默认为8080,可以不用设置

server.port=8081

第四步:创建controller

package com.springboot.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class HelloController {
	
	@GetMapping("/hello")
	public String hello() {
		return "hello spring security";
	}

}

第五步:启动springboot项目,浏览器访问

访问localhost:8081/test/hello回车后,他会变成如下图

springsecurity入门案例_第2张图片

默认用户名为:user,密码在启动控制台可以找到

springsecurity入门案例_第3张图片

输入用户名、密码便可以访问到

springsecurity入门案例_第4张图片

你可能感兴趣的:(#,SpringSecurity,springsecurity)