新建project
打开IntelliJ IDEA,新建project。
image.png
image.png
image.png
工程新建后生成的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>
启动DemoApplication.java,默认启动端口是8080,在浏览器访问http://localhost:8080,会出现如下页面:
image.png
这是spring security的默认登录页面,用户名是user,密码在启动时已经生成,如下图所示:
image.png
输入正确的用户名和密码后如下:
image.png
出现这个画面是因为没有配置登录成功后的页面url,默认是“/”。我们可写一个controller相应默认页面“/”,代码如下:
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>";
}
}
重新启动,登录,结果如下:
image.png
自定义用户名和密码
可以在application.properties中配置:
spring.security.user.name=demo
spring.security.user.password=demo
重新启动后用demo/demo可以成功登录。
配置用户认证(authentication)
新建一个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();
}
}