Gần đây tôi bắt đầu triển khai hệ thống bảo mật dựa trên mã thông báo với angularjs và mvc mùa xuân. Ý tưởng là như sau: 1. Truy cập/người dùng/xác thực để nhận mã bảo mật và lưu mã thông báo vào bộ nhớ cục bộ 2. Đối với mỗi yêu cầu được khách hàng angularJS gửi, hãy sử dụng trình chặn để chèn tiêu đề X-Auth-Token theo yêu cầu.401 Không được phép do CORS khi gửi yêu cầu nhận mã thông báo người dùng
Trong back-end mùa xuân của tôi, tôi đã triển khai một AuthenticationTokenProcessingFilter và một CustomAuthenticationEntryPoint. Đầu tiên để trích xuất mã thông báo từ tiêu đề và kiểm tra xem mã đó có hợp lệ không và mã thứ hai trả lại trạng thái trái phép 401 khi yêu cầu không được xác thực.
Hãy tìm một số chi tiết về mã back-end của tôi
AuthenticationController.java
@RestController
@RequestMapping(value="user")
public class AuthenticationController {
@RequestMapping(value="authenticate", method = RequestMethod.POST)
public ResponseEntity<?> login(@RequestParam("email") String email,
@RequestParam("password") String password) {
//Check if user is valid and return token
}
}
SecurityConfig.java
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UsersRepository usersRepo;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {...}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(
new AuthenticationTokenProcessingFilter(usersRepo),
UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(this.corsFilter(), UsernamePasswordAuthenticationFilter.class)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf().disable().exceptionHandling()
.and()
.httpBasic()
.authenticationEntryPoint(new CustomAuthenticationEntryPoint())
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/user/authenticate").permitAll()
.antMatchers("/**").authenticated()
.anyRequest().authenticated();
}
@Bean
public CORSFilter corsFilter() {
return new CORSFilter();
}
}
CORSFilter.java
public class CORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, Origin, X-Auth-Token");
response.addHeader("Access-Control-Expose-Headers", "X-Auth-Token");
chain.doFilter(req, res);
}
}
Bây giờ tôi đang sử dụng mã angularjs sau đây để truy vấn điểm cuối/người dùng/xác thực không phải là phía sau tường lửa
return $http.post(baseUrl + 'user/authenticate', 'email='+username+'&password='+password,
{
headers : {
'content-type' : 'application/x-www-form-urlencoded'
}
}
);
Khi tôi sử dụng mã trên, mọi thứ hoạt động. Tuy nhiên Nếu tôi loại bỏ tham số header từ yêu cầu, máy khách angularjs của tôi gửi một yêu cầu OPTION (chứ không phải là một yêu cầu POST - tôi tưởng tượng điều này liên quan đến bộ lọc CORS của tôi) và kết thúc của tôi gửi một phản hồi 401 trái phép.
Bạn có thể vui lòng cho tôi biết thêm một số chi tiết tại sao điều này xảy ra không?
Cảm ơn bạn trước!
Tôi đã thấy câu hỏi liên quan http://stackoverflow.com/questions/24926226/best-practices-for-handling-cors-between-spring-and-angular-js và http://stackoverflow.com/questions này/12111936/angularjs-perform-an-options-http-request-for-a-nguồn gốc chéo – allenhwkim