У меня есть передний конец, написанный в AngularJS, и backend Spring MVC. Идея, которая у меня была, заключалась в том, чтобы обеспечить только службы REST API и использовать перехватчик в AngularJS для перенаправления пользователя на страницу входа в систему при выполнении несанкционированного вызова службы. Проблема, с которой я столкнулся сейчас, заключается в том, что, пока вызывается служба, страница отображается кратковременно до перенаправления пользователя. Что я могу с этим поделать? Или этот подход принципиально испорчен?AngularJS и Spring MVC security
Это перехватчик:
$httpProvider.interceptors.push(function ($q, $location) {
return {
'responseError': function(rejection) {
var status = rejection.status;
if (status == 401 || status == 403) {
$location.path("/login");
} else {
}
return $q.reject(rejection);
}
};});
Моя конфигурация безопасности:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService customUserDetailsService;
@Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**")
.authorizeRequests()
.anyRequest().authenticated();
}
@Bean(name="myAuthenticationManager")
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
Контроллер Логин:
@RequestMapping(value = "/login", method = RequestMethod.POST, produces="application/json")
@ResponseBody
public String login(@RequestBody User user) {
JSONObject result = new JSONObject();
UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
try {
Authentication auth = authenticationManager.authenticate(token);
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(auth);
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession(true);
session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
result.put("isauthenticated", true);
} catch (BadCredentialsException e) {
result.put("isauthenticated", false);
}
return result.toString();
}
Спасибо! Я немного экспериментирую с обоими подходами. Может быть, я могу показать spinner, пока, по крайней мере, одна служба не будет успешно вызвана. – user3170702