首先,需要添加所需maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.添加配置:
package com.springboot.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("java12345").roles("USER");
System.out.println("33333");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/logins.html")
.defaultSuccessUrl("/welcome.html")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.csrf().disable();
System.out.println("222222222");
super.configure(http);
}
@Override
public void configure(WebSecurity web) throws Exception {
//解决静态资源被拦截的问题
web.ignoring().antMatchers("/css/**");
}
}
当然,里面的两个地址都需要一个controller
登录页面表单:
<body>
<div class="container">
<h3 align="center">这是一个带有登录框的主页</h3>
<form class="form-signin" action="/logins.html" method="post">
<h2 class="form-signin-heading">请 登 录</h2>
<input type="text" class="form-control" placeholder="账号" name = "username"/>
<input type="password" class="form-control" placeholder="密码" name="password"/>
<button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
</form>
</div>
</body>