Iri*_*ram 20 java spring spring-security ionic2 angular
我在我的Web应用程序中集成spring security(即登录部分)时遇到了一些麻烦.我的BackEnd在localhost:8080上运行,FrontEnd(Ionic 2与AngularJS 2)在localhost:8100上运行.我设法登录(至少我是这么认为),但其他请求变得不可用,我在Chrome开发者控制台中收到以下错误:
XMLHttpRequest cannot load http://localhost:8080/company/getAll. Response for preflight is invalid (redirect)
Run Code Online (Sandbox Code Playgroud)
当使用Postman进行测试时,它似乎正在工作,我登录然后我能够在http:// localhost:8080/company/getAll上执行POST请求,一切都按预期工作.
据推测,我错过了某些东西(比如令牌)但却无法弄清楚是什么.我是Ionic和Spring Security的新手,所以请原谅我,如果这是微不足道的话.我尝试使用谷歌搜索各种教程,但无法找到任何东西(大多数都使用JSP).
我怎么能让这个工作?我的前端请求应该怎么样?
这是我从BackEnd控制器登录的方法:
@RequestMapping(value = "/login", method = RequestMethod.GET)
@CrossOrigin(origins = "*")
public ResponseEntity<GeneralResponse> login(Model model, String error, String logout) {
System.out.println("LOGIN"+model.toString());
if (error != null) {
System.out.println("1.IF");
model.addAttribute("error", "Your username and password is invalid.");
}
if (logout != null) {
System.out.println("2.IF");
model.addAttribute("message", "You have been logged out successfully.");
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new GeneralResponse(true, "FAILURE: Error"));
}
Run Code Online (Sandbox Code Playgroud)
这是我的WebSecurityConfig:
@Configuration
@EnableWebSecurity
@ComponentScan("com.SAB.service")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**", "/registration").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/user/login")
.permitAll()
.and()
.logout()
.permitAll();
http
.csrf().disable();
http.formLogin().defaultSuccessUrl("http://localhost:8100/", true);
//.and().exceptionHandling().accessDeniedPage("/403")
//.and().sessionManagement().maximumSessions(1).maxSessionsPreventsLogin(true);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
}
Run Code Online (Sandbox Code Playgroud)
最后我的FrontEnd代码负责登录:
login(){
var body = 'username='+this.loginForm.controls['username'].value+'&password='+this.loginForm.controls['password'].value;
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
//headers.append("Access-Control-Allow-Origin", "*");
this.http
.post('http://localhost:8080/user/login',
body, {
headers: headers
})
.subscribe(data => {
console.log('ok');
console.log(data)
}, error => {
console.log(JSON.stringify(error.json()));
});
}
Run Code Online (Sandbox Code Playgroud)
如果您需要任何其他详细信息,请告诉我,我会提供.
提前致谢!
我没有得到Access-COntroll-Origin错误,但我试图根据评论改变它,现在我收到"无效的CORS请求"
编辑: 这是Spring Security日志.但是,即使FrontEnd正在调用POST,Spring也只注册OPTIONS请求而不注册POST.
************************************************************
Request received for OPTIONS '/login':
org.apache.catalina.connector.RequestFacade@18859793
servletPath:/login
pathInfo:null
headers:
host: localhost:8080
connection: keep-alive
access-control-request-method: POST
origin: http://localhost:8100
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36
access-control-request-headers: access-control-allow-origin
accept: */*
referer: http://localhost:8100/
accept-encoding: gzip, deflate, sdch, br
accept-language: en-US,en;q=0.8
Security filter chain: [
WebAsyncManagerIntegrationFilter
SecurityContextPersistenceFilter
HeaderWriterFilter
CorsFilter
LogoutFilter
UsernamePasswordAuthenticationFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
]
************************************************************
2017-05-12 19:18:28.527 DEBUG 16500 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : /login at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2017-05-12 19:18:28.527 DEBUG 16500 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : /login at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2017-05-12 19:18:28.527 DEBUG 16500 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
2017-05-12 19:18:28.527 DEBUG 16500 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
2017-05-12 19:18:28.529 DEBUG 16500 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : /login at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2017-05-12 19:18:28.529 DEBUG 16500 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : /login at position 4 of 12 in additional filter chain; firing Filter: 'CorsFilter'
2017-05-12 19:18:28.541 DEBUG 16500 --- [nio-8080-exec-1] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@5baaaa2b
2017-05-12 19:18:28.541 DEBUG 16500 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2017-05-12 19:18:28.541 DEBUG 16500 --- [nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
Run Code Online (Sandbox Code Playgroud)
更新:
所以在添加了接受的答案中建议的CORSFilter之后,我还必须在前端修改我的请求,以便在每个请求上发送带有JSESSIONID的cookie.我不得不将以下内容添加到我的所有请求中:
let options = new RequestOptions({ headers: headers, withCredentials: true });
这似乎是与CORS配置相关的问题.浏览器确实会在您的实际GET调用之前发出OPTION预检请求.我对这方面的知识不多,但您可以尝试将下面的过滤器添加到弹簧后端.
public class CORSFilter extends GenericFilterBean {
public void doFilter(ServletRequest request, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse response = (HttpServletResponse) res;
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.addHeader("Access-Control-Max-Age", "3600");
response.addHeader("Access-Control-Allow-Headers", "X-Requested-With, X-Auth-Token");
response.addHeader("Access-Control-Allow-Credentials", "true");
if(req.getMethod().equalsIgnoreCase("options")){
return;
}
chain.doFilter(request, response);
}
}
Run Code Online (Sandbox Code Playgroud)
并在WebSecurityConfig的configure方法中添加以下行.
.addFilterBefore(new CORSFilter(), ChannelProcessingFilter.class);
| 归档时间: |
|
| 查看次数: |
5233 次 |
| 最近记录: |