[英]Manual Spring security implementation with a call from angular and password encoded
我很抱歉我的英語不好..
我正在使用 Spring Boot、Spring Security 模塊和 Angular。 我也有一個自定義數據庫。
我改變了我所有的項目架構。 之前,我使用登錄表單在 HTML 中調用 thymeleaf : th:action="@/login" 。 現在,我刪除了 thymeleaf,所以我用 AngularJS 實現了一個簡單的表單。
我想做的是:
之前我在使用thymeleaf的時候,是通過攔截請求自動調用這個函數的。 但現在我需要手動調用它。 我怎樣才能做到這一點?
我在這里發布我的部分代碼:
我的 login.html 中的表單
<form autocomplete="off">
<label>{{'login.username' | translate}}</label>
<input class="form-control" type="text" name="username" ng-change="message = false" ng-model="username" required/>
<label>{{'login.password' | translate}}</label>
<input class="form-control" type="password" name="password" ng-change="message = false" ng-model="password" required/>
<button type="submit" class="btn btn-default" ng-click="login()">{{'login.button' | translate}}</button>
</form>
我在 login.js 中的角度函數
$scope.login = function(){
var dataToSend = {
username : $scope.username,
password : $scope.password
}
$http.post('/login', dataToSend).success(function(){
alert("ok");
}).error(function () {
alert("skdjs");
})
}
我的 UserController.java 中的 java 方法(我需要用你的提議來實現這個方法)
@RequestMapping(value="/login", method = RequestMethod.POST)
public JSONObject login(HttpServletRequest request, HttpServletResponse response, @RequestBody User user) {
}
我可以輕松獲得密碼和用戶名,但我沒有方法 getAuthorities。 我有一個加密的密碼,你可以在我的SecurityConfig.java 中看到
有關注銷的信息,我有這個並且它有效
@RequestMapping(value="/user/logout", method = RequestMethod.GET)
public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "redirect:/login?logout";
}
最后,我的文件SecurityConfig.java沒有調用我的方法configAuthentication 。
package betizy.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import javax.sql.DataSource;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
DataSource dataSource;
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
System.out.println("djfkdjfdkfjkd");
auth.jdbcAuthentication().dataSource(dataSource)
.passwordEncoder(passwordEncoder())
.usersByUsernameQuery(
"select use_username, use_password, use_enabled from use_user where use_username=?")
.authoritiesByUsernameQuery(
"select use_username, usr_role from usr_user_role, use_user where use_id = usr_use_id and use_username=?");
}
@Bean
public PasswordEncoder passwordEncoder(){
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
//.antMatchers("/hello").access("hasRole('ROLE_ADMIN')")
.antMatchers( "/",
"/**",
"/user/activate",
"/user/activate/**",
"/user/create",
"/user/register",
"/webjars/**",
"/templates/**",
"/static/**",
"/favicon.ico"
).permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.usernameParameter("username").passwordParameter("password")
.and()
.logout().permitAll()
.and()
.exceptionHandling().accessDeniedPage("/403")
.and()
.csrf().disable();
}
}
非常感謝您的幫助!
PS:我閱讀了 Spring security Angular 教程,但我想使用我前面描述的方法
編輯
我正在使用 Spring Boot,我的 application.properties 是:
spring.datasource.url = jdbc:mysql://localhost/betizy
spring.datasource.username = root
spring.datasource.password =
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
這就是我的 Spring Security 配置
你可以使用 org.springframework.security.authentication.AuthenticationManager
@Autowired
private AuthenticationManager authenticationManager;
@RequestMapping(value="/login", method = RequestMethod.POST)
public JSONObject login(HttpServletRequest request, HttpServletResponse response, @RequestBody User user) {
//does the authentication
final Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
user.getUsername(),
user.getPassword()
)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
//just an example of return - you could easily just return the 200 code or smth
return Json.createObjectBuilder()
.add("firstName", user.getFirstName())
.add("lastName", user.getLastName())
.add("status", HttpStatus.OK);
}
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.