我已經使用Spring初始化程序,嵌入式Tomcat,Thymeleaf模板引擎和程序包生成了一個Spring Boot Web應用程序作爲可執行JAR文件。使用inMemoryAuthentication with Spring Boot
技術:
春季啓動1.4.2.RELEASE,春天4.3.4.RELEASE,Thymeleaf 2.1.5.RELEASE,Tomcat的嵌入8.5.6時,Maven 3,Java的8
這是我的安全配置類:
@Configuration
@EnableWebSecurity
@PropertySource("classpath:/com/tdk/iot/config/app-${APP-KEY}.properties")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${securityConfig.formLogin.loginPage}")
private String loginPage;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage(loginPage)
.permitAll()
.loginProcessingUrl("/login")
.failureUrl("/login.html?error=true")
.defaultSuccessUrl("/books/list")
.and()
.exceptionHandling()
.accessDeniedPage("/denied")
.and()
.authorizeRequests()
.antMatchers("/mockup/**").permitAll()
.antMatchers("/books/**").permitAll()
.antMatchers("/welcome/**").authenticated()
.and()
.logout()
.permitAll()
.logoutSuccessUrl("/index.html");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.passwordEncoder(new StandardPasswordEncoder())
.withUser("test1").password("test1").roles("ADMIN").and()
.withUser("test2").password("test2").roles("USER").and()
.withUser("test3").password("test3").roles("SUPERADMIN");
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertyDefaultConfig() {
return new PropertySourcesPlaceholderConfigurer();
}
}
這裏的LoginController
@Controller
public class LoginController {
@RequestMapping(value={ "/", "/tdk/login"}, method = { RequestMethod.POST,RequestMethod.GET})
public String welcome(Map<String, Object> model) {
return "tdk/login";
}
}
和模板:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<div class="wrap">
<div class="login">
<div class="logo"></div>
<form th:action="@{/login.html}" method="post">
<p th:if="${loginError}" class="error">Wrong user or password</p>
<div class="input_label"><i class="fa fa-user"></i><input type="text" name="user" placeholder="User" /></div>
<div class="input_label"><i class="fa fa-key"></i><input type="password" name="pass" placeholder="Password" /></div>
<input type="submit" value="LOGIN" />
</form>
<div class="forget">
<!-- <a href="#">Do you forgot your password?</a><br/> -->
<br/>
</div>
</div>
</div>
</body>
</html>
但是當我測試1/test1的訪問,我得到這個錯誤:
爲@RequestMappingWhitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun Mar 05 20:16:11 CET 2017 There was an unexpected error (type=Method Not Allowed, status=405). Request method 'POST' not supported
結帳http://docs.spring.io/spring-security/site/docs/3.2.0.RELEASE/guides/form.html – hya
BTW:你在你的代碼中有更多的錯誤。默認參數名稱是'username'和'password',但是您在登錄頁面使用'user'和'pass'。您必須更改配置或登錄頁面。 – dur