新建project
打開(kāi)IntelliJ IDEA抽莱,新建project。
工程新建后生成的pom文件主要添加了如下依賴:
<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>
<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>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
啟動(dòng)DemoApplication.java京腥,默認(rèn)啟動(dòng)端口是8080被冒,在瀏覽器訪問(wèn)http://localhost:8080古今,會(huì)出現(xiàn)如下頁(yè)面:
這是spring security的默認(rèn)登錄頁(yè)面惶楼,用戶名是user右蹦,密碼在啟動(dòng)時(shí)已經(jīng)生成,如下圖所示:
輸入正確的用戶名和密碼后如下:
出現(xiàn)這個(gè)畫(huà)面是因?yàn)闆](méi)有配置登錄成功后的頁(yè)面url,默認(rèn)是“/”歼捐。我們可寫(xiě)一個(gè)controller相應(yīng)默認(rèn)頁(yè)面“/”何陆,代碼如下:
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController {
@GetMapping("/")
public String home() {
return "<h1>this is my demo</h1>";
}
}
重新啟動(dòng),登錄豹储,結(jié)果如下:
自定義用戶名和密碼
可以在application.properties中配置:
spring.security.user.name=demo
spring.security.user.password=demo
重新啟動(dòng)后用demo/demo可以成功登錄甲献。
配置用戶認(rèn)證(authentication)
新建一個(gè)class,名字隨便颂翼,我這里命名為SecurityConfig,代碼如下:
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("demo1")
.password("demo1")
.roles("USERS")
.and()
.withUser("demo2")
.password("demo2")
.roles("ADMIN");
}
@Bean
public PasswordEncoder getPasswordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
}