我有一个带有jwt身份验证的spring boot rest api.问题是我无法摆脱默认的403 Access Denied rest响应,如下所示:
{
"timestamp": 1516206966541,
"status": 403,
"error": "Forbidden",
"message": "Access Denied",
"path": "/api/items/2"
}
Run Code Online (Sandbox Code Playgroud)
我创建了自定义AccessDeniedHandler:
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest req,
HttpServletResponse res,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
ObjectMapper mapper = new ObjectMapper();
res.setContentType("application/json;charset=UTF-8");
res.setStatus(403);
res.getWriter().write(mapper.writeValueAsString(new JsonResponse()
.add("timestamp", System.currentTimeMillis())
.add("status", 403)
.add("message", "Access denied")));
}
}
Run Code Online (Sandbox Code Playgroud)
并将其添加到WebConfig类
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
private UserDetailsService userDetailsService;
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
public WebSecurity(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
this.userDetailsService …
Run Code Online (Sandbox Code Playgroud) 该问题与ASP.NET Core 2.0中的身份验证有关。
之后PasswordSignInAsync()
的result
有一个状态的成功。所以我重定向到行动Chat
在StaticController
。
[HttpPost("login")]
public async Task<ActionResult> Login([Bind] LoginModel lm) {
if (!ModelState.IsValid)
return BadRequest(ModelState);
var result = await _signInManager.PasswordSignInAsync(lm.Username, lm.Password, false, false);
if (result.Succeeded)
return RedirectToAction("Login", "Static");
else
return BadRequest(new { message = "Invalid username or password" });
}
Run Code Online (Sandbox Code Playgroud)
StaticController.Chat()
[HttpGet("/chat")]
public ActionResult Chat() {
if (User.Identity.IsAuthenticated)
return File("~/chat/index.html", "text/html");
else
return RedirectToAction("Login", "Static");
}
Run Code Online (Sandbox Code Playgroud)
并且这里出现问题是因为User.Identity.IsAuthenticated始终为false。即使执行了Login()操作后,我从浏览器中调用localhost:5000/chat
它仍然是错误的。
这些是我找到的相关解决方案,但是它们都不起作用:
该解决方案已过时。我正在使用ASP.NET Core 2.0,但UseCookieAuthentication()
已过时。
PasswordSignInAsync成功后,User.Identity.IsAuthenticated始终为false
正如在此解决方案中指出的那样,在Login()操作之后调用SignInAsync之后,User.Identity.IsAuthenticated返回false,我应该再次调用Chat()方法(就像我所做的那样 …
在春季启动时发送休息响应的最佳方法是什么?另外我应该如何管理发送状态代码才能正确完成?
目前我使用ResponseEntity,但我怀疑这是最优雅的方式.
示例代码:
@PostMapping()
public ResponseEntity post(@Valid @RequestBody Item item, BindingResult bindingResult){
if (bindingResult.hasErrors()){
return new ResponseEntity<>(new ModelErrors(bindingResult), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(itemService.addItem(item), HttpStatus.CREATED);
}
Run Code Online (Sandbox Code Playgroud)
ModelErrors类扩展了HashMap类,只是获取并包装BindingResult的错误消息.
java ×2
rest ×2
spring ×2
asp.net ×1
c# ×1
controller ×1
httpresponse ×1
identity ×1
response ×1