33

JSON通信を完全に使用するspring/spring-mvcのアプリケーションがあります。ここで、JSON 経由で Spring Security 3 (LdapAuthenticationProvider を使用) でアプリケーションを認証する必要があります。

デフォルトのSpring Seurity送信フォームには、次のようなPOSTが必要です:

POST /myapp/j_spring_security_check HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 32
Host: 127.0.0.1:8080
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)

j_username=myUsername&j_password=myPass

しかし、次のような JSON オブジェクトを渡したい:

{"j_username":"myUsername","j_password":"myPass"}

私はthisthis otherまたはthis oneのような多くの投稿を読みましたが、すべての ajax ケースで上記のような POST が行われます。

何か案は?

4

8 に答える 8

19
public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response){
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        LoginRequest loginRequest = this.getLoginRequest(request);

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword());

        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }

    private LoginRequest getLoginRequest(HttpServletRequest request) {
        BufferedReader reader = null;
        LoginRequest loginRequest = null;
        try {
            reader = request.getReader();
            Gson gson = new Gson();
            loginRequest = gson.fromJson(reader, LoginRequest.class);
        } catch (IOException ex) {
            Logger.getLogger(AuthenticationFilter.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                Logger.getLogger(AuthenticationFilter.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        if (loginRequest == null) {
            loginRequest = new LoginRequest();
        }

        return loginRequest;
    }
}
于 2013-12-03T14:07:32.687 に答える
14

JSON を解析する独自のセキュリティ フィルターを作成できます。

http://docs.spring.io/spring-security/site/docs/3.0.x/reference/core-web-filters.html

BasicAuthenticationFilter を参照として使用できます。

http://docs.spring.io/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/authentication/www/BasicAuthenticationFilter.html

于 2013-10-21T17:33:28.117 に答える
5

この投稿によると、もう 1 つの方法は、Spring セキュリティ認証を Controller で直接手動で管理することです。
このようにして、JSON 入力を管理し、ログイン リダイレクトを回避するのは非常に簡単です。

@Autowired
AuthenticationManager authenticationManager;

@ResponseBody
@RequestMapping(value="/login.json", method = RequestMethod.POST)
public JsonResponse mosLogin(@RequestBody LoginRequest loginRequest, HttpServletRequest request) {
    JsonResponse response = null;

    try {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword());
        token.setDetails(new WebAuthenticationDetails(request));

        Authentication auth = authenticationManager.authenticate(token);
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(auth);

        if(auth.isAuthenticated()){
            HttpSession session = request.getSession(true);
            session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);

            LoginResponse loginResponse = new LoginResponse();
            loginResponse.setResponseCode(ResponseCodeType.SUCCESS);
            response = loginResponse;   
        }else{
            SecurityContextHolder.getContext().setAuthentication(null);

            ErrorResponse errorResponse = new ErrorResponse();
            errorResponse.setResponseCode(ResponseCodeType.ERROR);
            response = errorResponse;
        }   
    } catch (Exception e) {     
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setResponseCode(ResponseCodeType.ERROR);
        response = errorResponse;           
    }
    return response;
}
于 2013-10-24T22:19:32.527 に答える
1

Spring Boot アプリケーションで JSON 資格情報を使用してログインするために、 fl4loe.elvikからの回答を適用しました。注釈ベースの Bean 構成を使用しています。

参照されている回答では、認証マネージャーが挿入されるカスタム フィルターが作成されます。これを行うには、認証マネージャーが Spring Bean として存在する必要があります。これを行う方法に関するリンクは次のとおりです: https://stackoverflow.com/a/21639553/3950535

于 2018-10-26T10:17:53.557 に答える