0

私はGitHub でこの相互接続された 3 つのアプリのセットを分解することで Spring OAuth を研究していますが、このリンクの Spring OAuth 2 開発者ガイドも注意深く研究しています。 開発者ガイドには、/oauth/errorエンドポイントをカスタマイズする必要があると書かれていますが、オーバーライドを成功させるには、どの特定のコードを使用する必要があります/oauth/errorか?


最初の試み:


オーバーライドを行う最初の試みは、エラーをスローすることです。これは、このリンクでファイル共有サイトにアップロードしたデバッグ ログで確認できます。

まず、Spring が提供するコード要素をサンプル アプリで動作させることから始めました。

最初に、authserver上記のサンプル アプリのリンクで新しいコントローラー クラスをアプリに追加し、Spring のサンプル コードの一部を追加しました。WhiteLabelErrorEndpoint.javaこれは、このリンクで読むことができます。私の試みは次のとおりです。

package demo;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.HtmlUtils;

@Controller
public class CustomViewsController {

private static final String ERROR = "<html><body><h1>OAuth Error</h1><p>${errorSummary}</p></body></html>";

@RequestMapping("/oauth/error")
public ModelAndView handleError(HttpServletRequest request) {
    Map<String, Object> model = new HashMap<String, Object>();
    Object error = request.getAttribute("error");
    // The error summary may contain malicious user input,
    // it needs to be escaped to prevent XSS
    String errorSummary;
    if (error instanceof OAuth2Exception) {
        OAuth2Exception oauthError = (OAuth2Exception) error;
        errorSummary = HtmlUtils.htmlEscape(oauthError.getSummary());
    }
    else {
        errorSummary = "Unknown error";
    }
    model.put("errorSummary", errorSummary);
    return new ModelAndView(new SpelView(ERROR), model);
    }
}

そして、このリンクからコードをコピーして、SpelView.java上記のリンクで使用される次の String ハンドラー クラスを追加しました。

package demo;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.expression.MapAccessor;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.security.oauth2.common.util.RandomValueStringGenerator;
import org.springframework.util.PropertyPlaceholderHelper;
import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

/**
 * Simple String template renderer.
 * 
 */
class SpelView implements View {

    private final String template;

    private final String prefix;

    private final SpelExpressionParser parser = new SpelExpressionParser();

    private final StandardEvaluationContext context = new StandardEvaluationContext();

    private PlaceholderResolver resolver;

    public SpelView(String template) {
        this.template = template;
        this.prefix = new RandomValueStringGenerator().generate() + "{";
        this.context.addPropertyAccessor(new MapAccessor());
        this.resolver = new PlaceholderResolver() {
            public String resolvePlaceholder(String name) {
                Expression expression = parser.parseExpression(name);
                Object value = expression.getValue(context);
                return value == null ? null : value.toString();
            }
        };
    }

    public String getContentType() {
        return "text/html";
    }

    public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Map<String, Object> map = new HashMap<String, Object>(model);
        String path = ServletUriComponentsBuilder.fromContextPath(request).build()
                .getPath();
        map.put("path", (Object) path==null ? "" : path);
        context.setRootObject(map);
        String maskedTemplate = template.replace("${", prefix);
        PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper(prefix, "}");
        String result = helper.replacePlaceholders(maskedTemplate, resolver);
        result = result.replace(prefix, "${");
        response.setContentType(getContentType());
        response.getWriter().append(result);
    }

}
4

1 に答える 1

1

エラービューをオーバーライドするには、コントローラーを定義します。

@Controller
public class ErrorController {
    @RequestMapping("/oauth/error")
    public String error(Map<String,Object> model) {
       // .. do stuff to the model
       return "error";
    }
}

次に、「エラー」ビューを実装します。たとえば、Freemarker を使用して、Spring Boot アプリで、クラスパスの上部にある「templates」ディレクトリに「error.ftl」というファイルを作成します。

<html><body>Wah, there was an error!</body></html>

これはすべて単純な Spring MVC です。詳細については、Spring ユーザー ガイドを参照してください。

于 2016-04-19T07:46:22.067 に答える