gpt4 book ai didi

java-ee-6 - ServletRequestListener - 获取用户主体返回 null

转载 作者:行者123 更新时间:2023-12-04 05:01:36 25 4
gpt4 key购买 nike

我有一个使用 HTTP-Basic 身份验证保护的 Web 应用程序。
我还使用 ServletRequestListener 实现了一个过滤器界面。现在,当过滤器调用 requestInitialized 时方法,请求的getUserPrincipal-Method返回null。但是当我检查请求 header 时,授权 header 设置为加密值。这是代码:

@Override
public void requestInitialized(ServletRequestEvent e) {

HttpServletRequest request = (HttpServletRequest) e.getServletRequest();

//p is null
Principal p = request.getUserPrincipal();

Enumeration<String> enH = request.getHeaders("Authorization");
while (enH.hasMoreElements()) {
String s = enH.nextElement();
System.out.println(s);
//prints.
//Basic c3RhY2tvdmVyZmxvdzpteXBhc3N3b3Jk
}
}

为什么 userprincipal 没有初始化?

最佳答案

您可能没有为嵌入式码头设置所需的安全层。

这是一个 exampleJetty embedded examples source tree 中找到.

package org.eclipse.jetty.embedded;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.HashLoginService;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.authentication.BasicAuthenticator;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.security.Constraint;

public class SecuredHelloHandler
{
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);

LoginService loginService = new HashLoginService("MyRealm","src/test/resources/realm.properties");
server.addBean(loginService);

ConstraintSecurityHandler security = new ConstraintSecurityHandler();
server.setHandler(security);

Constraint constraint = new Constraint();
constraint.setName("auth");
constraint.setAuthenticate( true );
constraint.setRoles(new String[]{"user", "admin"});

ConstraintMapping mapping = new ConstraintMapping();
mapping.setPathSpec( "/*" );
mapping.setConstraint( constraint );

Set<String> knownRoles = new HashSet<String>();
knownRoles.add("user");
knownRoles.add("admin");

security.setConstraintMappings(Collections.singletonList(mapping), knownRoles);
security.setAuthenticator(new BasicAuthenticator());
security.setLoginService(loginService);
security.setStrict(false);

// Your Handler (or Servlet) that should be secured
HelloHandler hh = new HelloHandler();

security.setHandler(hh);

server.start();
server.join();
}
}

关于java-ee-6 - ServletRequestListener - 获取用户主体返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16085324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com