欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Tomcat8配置Basic Authentication

程序员文章站 2022-07-12 17:59:18
...
一、使用Eclipse创建一个myapp JavaEE工程
二、配置用户、密码、角色
修改Tomcat的conf目录下的tomcat-users.xml文件,内容如下:
<role rolename="tomcat"/>
<role rolename="manager"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="manager" password="manager" roles="manager"/>

   三、配置web

   修改myapp/WEB-INF/web.xml文件

   在<web-app></web-app>标签中添加一下内容

 

<security-constraint>
<display-name>Security Constraint</display-name>
<web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>DELETE</http-method>
<http-method>GET</http-method>
<http-method>POST</http-method>
<http-method>PUT</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>tomcat</role-name>
<role-name>manager</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
<security-role>
<role-name>tomcat</role-name>
</security-role>
<security-role>
<role-name>manager</role-name>
</security-role>

 四、在浏览器地址栏输入http://localhost:8080/myapp-1.0/,如果没有输入用户和密码出现401

 
Tomcat8配置Basic Authentication
            
    
    博客分类: tomcat tomcatBasic认证 
 输入正确的用户和密码后

 
Tomcat8配置Basic Authentication
            
    
    博客分类: tomcat tomcatBasic认证 
 

五、在index.jsp添加以下代码

<%@page language="java" import="java.util.*" %>
<%@page language="java" import="org.apache.commons.codec.binary.Base64" %>

<%
Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = (String) headerNames.nextElement();
String headerValue = request.getHeader(headerName);
out.println(headerName + ": " + headerValue + "<br/>");
}

out.println("<hr/>");

String authHeader = request.getHeader("authorization");
String encodedValue = authHeader.split(" ")[1];
out.println(new String(Base64.decodeBase64(encodedValue)));

%>

 六、运行结果

accept: text/html, application/xhtml+xml, image/jxr, */*
accept-language: zh-CN
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393
accept-encoding: gzip, deflate
host: localhost:8080
connection: Keep-Alive
cache-control: no-cache
authorization: Basic dG9tY2F0OnRvbWNhdA==

tomcat:tomcat(dG9tY2F0OnRvbWNhdA==解密后结果)

 

  • Tomcat8配置Basic Authentication
            
    
    博客分类: tomcat tomcatBasic认证 
  • 大小: 78.9 KB
  • Tomcat8配置Basic Authentication
            
    
    博客分类: tomcat tomcatBasic认证 
  • 大小: 88.2 KB
相关标签: tomcat Basic认证