也可以在 application.properties 中指定用户名和密码,配置项为
spring.security.user.name=tomspring.security.user.password=123456Spring Boot 根据响应的Content-Type 提供不同的认证机制,分别为 Http Basic 和 Form-based ,比如返回的是application/json 时用Http Basic, 是text/html 时用 Form-based。
用个具体例子说明,在 Controller 里添加
@RequestMapping("/") @ResponseBody Map<String, String> home() { Map<String, String> map = new HashMap<>(); map.put("say", "Hello World!"); return map; }项目启动后,用一个浏览器http 请求插件构造请求,本文用的chrome 的Reslet Client 。
如上图用请求头的Content-Type 为text/html, 服务器相应代码, 从代码看出是登录页的html 代码
<html><head><title>Login Page</title></head><body οnlοad='document.f.username.focus();'> <h3>Login with Username and Password</h3><form name='f' action='/login' method='POST'> <table> <tr><td>User:</td><td><input type='text' name='username' value=''></td></tr> <tr><td>Password:</td><td><input type='password' name='password'></td></tr> <tr><td colspan='2'><input name="submit" type="submit" value="Login"></td></tr> <input name="_csrf" type="hidden" value="44c94267-0ad9-4b83-a1bb-de8553e6f8dc" > </table> </form></body></html>如上图把请求头的Content-Type 改为application/json, 另外添加了Authorizaiton 参数,后台返回
{"say":"Hello World!"}说明次请求通过登录认证,采用认证机制是Http Basic。
上面例子中可以看到后台返回的是Spring Security 默认的登录页,一般都要更改为自己的,那如何更改呢?
Spring Boot 为我们预留了扩展类 WebSecurityConfigurerAdapter
创建一个类:MyWebSecurityConfigurerAdapter 继承此类,代码如下
@Configuration public class MyWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().authenticated(). and().formLogin().loginPage("/login").permitAll(). and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll(); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().mvcMatchers("/static/**"); } }在Controller 里添加/login 映射
@RequestMapping("/login") public String login(){ return "login"; }在resources/templates 下创建 login.html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <title>Login page</title> <meta charset="utf-8" /> <link rel="stylesheet" href="/static/css/main.css" th:href="@{/static/css/main.css}" /> </head> <body> <h1>Login page</h1> <p>Example user: user / password</p> <p th:if="${loginError}" class="error">Wrong user or password</p> <form th:action="@{/login}" method="post"> <label for="username">Username</label>: <input type="text" id="username" name="username" autofocus="autofocus" /> <br /> <label for="password">Password</label>: <input type="password" id="password" name="password" /> <br /> <input type="submit" value="Log in" /> </form> <p><a href="/" th:href="@{/}">Back to home page</a></p> </body> </html>启动项目,访问http://localhost:8080, 会重定向到/login
源码下载
======================================
单页表单,简单易用 https://www.dan-ye.com,帮您在线收集各类数据