Spring Security 01- 將 Spring security 引入到工程

Spring security 系列博客目錄

對應源代碼

開篇

最近一段時間學習了 Spring Security,併成功整合到了項目中(基於Sping-boot2.x)。在此準備將踩坑過程記錄一下,順便講述下如何一步一步應用到項目中的。java

建立一個 Springboot 工程(springboot2.x)

https://github.com/nimo10050/spring-security-sample.gitgit

引入 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>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.7.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>

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

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

	</dependencies>

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

</project>

新建一個 Controller 類

package com.example.demo.controller;

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

@RestController
public class IndexController {

	@GetMapping("/hello")
	public Object sayHello(){
		return "hello world";
	}


}

啓動項目

項目啓動成功後, 用瀏覽器訪問 http://localhost:8080/hello 正常狀況下瀏覽器會打印出來 "hello world" 字符串。可是咱們由於咱們引入了 Spring Security 依賴。瀏覽器會自動跳轉到 http://localhost:8080/login 。以下圖:github

如何才能獲得咱們想要的頁面

用戶名默認是 user,源碼中能夠查到。密碼在項目啓動時已經在控制檯打印出來了。 web

輸入用戶名和密碼spring

相關文章
相關標籤/搜索