Search code examples
javarestauthenticationbasic-authentication

Java Rest Basic Authentication


I try my first steps with Java Rest Services. It should be with BASIC Authentication. I use Glassfish 4.1.1. This is my ToDo class. It doesn't work. I don't know why and I hope that someone can help me.

I use one class as root class. One service class and a class which collects the services.

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app>
    <context-root>/RestServiceBasicAuth</context-root>
    <security-role-mapping>
        <role-name>asadmin</role-name>
        <group-name>asadmin</group-name>

    </security-role-mapping>
</glassfish-web-app>

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">

    <servlet>
        <servlet-name>javax.ws.rs.core.Application</servlet-name>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>javax.ws.rs.core.Application</servlet-name>
        <url-pattern>/rest-api</url-pattern>
    </servlet-mapping>

    <security-constraint>

        <web-resource-collection>
            <web-resource-name>RestServiceBasicAuth</web-resource-name>
            <url-pattern>/RestServiceBasicAuth/rest-api/todos</url-pattern>
            <http-method>GET</http-method>
             <http-method>POST</http-method>
             <http-method>PUT</http-method>
             <http-method>HEAD</http-method>
        </web-resource-collection>

        <auth-constraint> 
            <role-name>asadmin</role-name>
        </auth-constraint>

        <user-data-constraint>
            <transport-guarantee>CONFIDENTIAL</transport-guarantee>
        </user-data-constraint>

    </security-constraint>

    <security-role>
        <role-name>asadmin</role-name>
    </security-role>

    <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>admin-realm</realm-name>
    </login-config>

</web-app>

Solution

  • I think you should replace

    <url-pattern>/RestServiceBasicAuth/rest-api/todos</url-pattern>
    

    with

    <url-pattern>/rest-api</url-pattern>