前提・実現したいこと
フロントエンド(Reactjs)からバックエンド(Spring boot)のサーバーにPOSTしJWTを受け取るシステムです。
postmanでは、
method: POST
URL: http:locaclhost:8080/api/auth/login
body:{
"userName":"user",
"password":"pass",
}
を投げればステータス200がちゃんと返ってきます。
フロントエンド側はステータスコード403が返ってきます。
発生している問題・エラーメッセージ
バックエンド側のエラー文
2021-12-24 17:59:48.639[0;39m [31mERROR[0;39m [35m20772[0;39m [2m---[0;39m [2m[nio-8080-exec-6][0;39m [36mo.a.c.c.C.[.[.[/].[dispatcherServlet] [0;39m [2m:[0;39m Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because the return value of "javax.servlet.http.HttpServletRequest.getHeader(String)" is null
フロントエンド側のエラー文
Access to XMLHttpRequest at 'http://localhost:8080/api/auth/login' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. POST http://localhost:8080/api/auth/login net::ERR_FAILED 401
authRequest
{"userName": 'user', "password": 'pass'}
該当のソースコード
java
//Controller @PostMapping("/api/auth/login") public ResponseEntity<?> login(@RequestBody AuthenticationRequest authenticationRequest)throws InvalidKeySpecException, NoSuchAlgorithmException { final Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken( authenticationRequest.getUsename(), authenticationRequest.getPassword())); SecurityContextHolder.getContext().setAuthentication(authentication); //トークン生成 User user=(User)authentication.getPrincipal(); String jwtToken=jwtprovider.createToken(user); //レスポンス生成 LoginResponse response=new LoginResponse(); response.setToken(jwtToken); return ResponseEntity.ok(response); } }
javascript
export const userLogin=(authRequest)=>{ return axios({ method:'POST', url:`${process.env.hostUrl||'http://localhost:8080'}/api/auth/login`, data:authRequest }) }
javascript
const LoginPage=({loading,error,...props})=>{ const [values, setValues] = useState({ userName: '', password: '' }); const handleSubmit=(evt)=>{ evt.preventDefault(); props.authenticate(); userLogin(values).then((response)=>{ console.log("response",response); if(response.status===200){ props.setUser(response.data); } else{ props.loginFailure('Something Wrong!Please Try Again'); } }).catch((err)=>{ if(err && err.response){ switch(err.response.status){ case 401: console.log("401 status"); props.loginFailure("Authentication Failed.Bad Credentials"); break; default: props.loginFailure('Something Wrong!Please Try Again'); } } else{ props.loginFailure('Something Wrong!Please Try Again'); } }); } return ( <div className="login-page"> ... <input id="username" type="text" className="form-control" minLength={2} value={values.userName} name="userName" required /> ... <input id="password" type="password" className="form-control" minLength={2} value={values.password} name="password" required/> ... <button type="submit">submit</button> ... </div> ) }
補足情報(FW/ツールのバージョンなど)
STS4
npx create-react-appよりプロジェクト作成
package.json
json
"axios": "^0.24.0", "react": "^17.0.2",
まだ回答がついていません
会員登録して回答してみよう