【问题标题】:JAX-RS REST API Basic AuthenticationJAX-RS REST API 基本身份验证
【发布时间】:2016-06-08 05:26:57
【问题描述】:

我正在尝试实施基本身份验证以某种方式保护我的其余 api。为了测试,我尝试使用下面的代码来过滤包含用户的 url 参数,但它不会在未经授权的情况下中止请求。最重要的是我需要以仅更新和删除需要使用相应的用户名和密码授权的方式来实现它。其他我不想过滤的东西。我有一个具有用户名和密码(加密)属性的用户类。因此,如果 url 在 users/{userID} 上包含 PUT 或 delete 方法,我希望它使用该特定用户的用户名和密码进行验证。我在下面列出了模型、资源和过滤器类的代码.. 我真的需要你的帮助。提前致谢。

过滤器类。

package Authentication;

import java.io.IOException;
import java.util.List;
import java.util.StringTokenizer;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import org.glassfish.jersey.internal.util.Base64;


@Provider
public class SecureFilter implements ContainerRequestFilter {

    private static final String Auth_Header = "Authorization";
    private static final String Auth_Header_Prefix = "Basic ";

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        if (requestContext.getUriInfo().getPath().contains("users")) {
            List<String> authHeader = requestContext.getHeaders().get(Auth_Header);
            if (authHeader != null && authHeader.size() > 0) {
                String authToken = authHeader.get(0);
                authToken = authToken.replaceFirst(Auth_Header_Prefix, "");
                String decodedString = Base64.decodeAsString(authToken);
                StringTokenizer tokenizer = new StringTokenizer(decodedString, ":");
                String userName = tokenizer.nextToken();
                String password = tokenizer.nextToken();
                if ("user".equals(userName) && "password".equals(password)) {
                    return;
                }
                Response unauthorizedstatus = Response
                        .status(Response.Status.UNAUTHORIZED)
                        .entity("these resources needs authorization. ")
                        .build();
                requestContext.abortWith(unauthorizedstatus);

            }
        }

    }

} 

资源类:

import com.mycompany.samplehospital.model.Alert;
import com.mycompany.samplehospital.model.Message;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */


import com.mycompany.samplehospital.model.User;

import com.mycompany.samplehospital.Services.UserServices;
import com.mycompany.samplehospital.exception.objectNotFound;
import com.mycompany.samplehospital.Services.AlertServices;
import com.mycompany.samplehospital.Services.MessageServices;

import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 *
 * @author sandesh poudel
 */
@Produces(MediaType.APPLICATION_XML)
@Path("/users")
public class userResources {


 UserServices service ;
 public userResources() throws Exception{
     service = new UserServices();
 }





    @GET
    @Produces(MediaType.APPLICATION_XML)
    public List<User> getAllUser(){
    return UserServices.getUsers();


    }
    @Path("/{userId}")

    @GET
    @Produces(MediaType.APPLICATION_XML)
    public User getUser(@PathParam("userId") int ID ) throws Exception{
        User myUserList = service.getUser(ID);
        if (myUserList == null){
        throw new objectNotFound("User not Found"); 
        }else {
            return myUserList;
        }

    }


    @POST
    @Produces(MediaType.APPLICATION_XML)
      @Consumes(MediaType.APPLICATION_XML)


    public User addUser(User user ) throws Exception{

        return service.AddUser(user);



    }
}


    @PUT
        @Path("/{userId}")

    @Produces(MediaType.APPLICATION_XML)
      @Consumes(MediaType.APPLICATION_XML)


    public User updtaeUser(User user) throws Exception{

    return service.updateUser(user);

    }
    @DELETE 
      @Path("/{userId}")
       @Produces(MediaType.APPLICATION_XML)

    public User delUser(@PathParam("userId") int ID) throws Exception{

        return service.removeUser(ID);


    }
    @Path("/{userId}/messages")

    @GET
    @Produces(MediaType.APPLICATION_XML)

    public  List<Message> getAllMessageByUser(@PathParam("userId") int ID) throws Exception{
        MessageServices mservice = new MessageServices();

        List<Message> messageUserList = mservice.getAllMessageByUser(ID);
        if (messageUserList == null ){
            throw new objectNotFound("messages not Found"); 

        } return messageUserList;

        }
    @GET
    @Produces(MediaType.APPLICATION_XML)
    @Path("/{userId}/alerts")


    public List<Alert> AlertsResources(@PathParam("userId") int userId){
        AlertServices myAlert = new AlertServices();


        List<Alert> newAlertUserList = myAlert.getAllAlertByUser(userId) ;
        if (newAlertUserList == null){
            throw new objectNotFound("messages not Found"); 

        } return newAlertUserList;


    }

模型类用户

package com.mycompany.samplehospital.model;

import java.io.Serializable;
import java.util.Map;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import Authentication.HashPassword;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author sandeshpoudel
 */
@XmlRootElement

public  class User implements Serializable {
    /**
     * 
     */

    private static final long serialVersionUID = 1L;
    private String title;
    private int age;
    private String Sex;
    private String Address;
    private int phoneNo;
    private String fullName;
    private int id;
    private Map<Integer, Message> allMessage;
    private Map<Integer,Alert> allAlerts;
    private String userName;
    private String passWord;
    private HashPassword hs ;





    public User() {
    }


    public User(int id,String fullName, String Sex, Integer age, Integer  phoneNumber, String Address, String title,String userName,String password) throws Exception {
        hs = new HashPassword();
        this.id= id;
        this.fullName = fullName;
        this.title = title;
        this.age = age;
        this.Sex = Sex;
        this.Address = Address;
        this.phoneNo = phoneNumber;
         setPassWord(password);
       // setPassWord(passWord) uncomment this and remove next line to execute on encryption mode;


        this.userName= userName;

    }
    public void setId(int id){
        this.id= id;
    }
    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setSex(String Sex) {
        this.Sex = Sex;
    }

    public void setAddress(String Address) {
        this.Address = Address;
    }

    public void setPhoneNo(int phoneNo) {
        this.phoneNo = phoneNo;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
    @XmlElement
    public String getPassWord() {
        return passWord;
    }

    public  void setPassWord(String passWord) throws Exception {

                hs = new HashPassword();
                this.passWord = hs.encrypt(passWord);


      //  this.passWord = passWord;
    }




@XmlElement
    public String getFullName() {
        return fullName;
    }
    /*

    */
@XmlElement
  public int getId(){
    return id;
}
@XmlElement

    public String getTitle() {
        return title;
    }
@XmlElement

    public int getAge() {
        return age;
    }
@XmlElement

    public String getSex() {
        return Sex;
    }
@XmlElement

    public String getAddress() {
        return Address;
    }
@XmlElement

    public int getPhoneNo() {
        return phoneNo;
    }
   @XmlTransient
    public Map<Integer, Message> getAllMessage() {
    return allMessage;
}
    public void setAllMessage(Map<Integer, Message> allMessage) {
    this.allMessage = allMessage;
}   @XmlTransient

    public Map<Integer, Alert> getAllAlerts() {
    return allAlerts;
}
    public void setAllAlerts(Map<Integer, Alert> allAlerts) {
    this.allAlerts = allAlerts;
    }


  @Override
    public String toString(){
        return (getSex() +" "+ getAddress()+" "+ getPhoneNo() +" "+ getFullName());
    }
}

【问题讨论】:

  • 可以设置spring security,查看this

标签: java web-services rest basic-authentication


【解决方案1】:

如果您在 Java EE 容器中运行应用程序,则可以使用 web.xml 中定义的标准 Web 安全性 https://docs.oracle.com/javaee/7/tutorial/security-webtier002.htm#GKBAA

或者如果你使用 Spring https://spring.io/guides/gs/securing-web/

【讨论】:

    【解决方案2】:

    基本身份验证是 servlet 规范的一部分。所以如果你在一个servlet容器中运行,就是这种情况,你可以只在web.xml中启用基本身份验证:

    <?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"
        version="3.1">
    
        <security-constraint>
            <web-resource-collection>
                <web-resource-name>all-content</web-resource-name>
                <url-pattern>/*</url-pattern>
            </web-resource-collection>
            <auth-constraint>
                <role-name>user</role-name>
            </auth-constraint>
        </security-constraint>
    
        <login-config>
            <auth-method>BASIC</auth-method>
            <realm-name>foo-realm</realm-name>
        </login-config>
    
        <security-role>
            <role-name>user</role-name>
        </security-role>
    </web-app>
    

    您还必须配置领域和角色,这取决于您的 servlet 容器实现。

    【讨论】:

      【解决方案3】:

      在一个示例 jax rs api 中,我通过在我的休息资源中获取 HttpServletRequest 来实现基本身份验证。

      我创建了一个 doAuthorize() 方法,它提取 Authentication 标头、解码和验证身份验证。

      然后我在需要它的资源路径方法中调用doAuthorize()。

      【讨论】:

        猜你喜欢
        • 2012-02-10
        • 2019-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-06
        • 2015-12-18
        • 2012-02-13
        相关资源
        最近更新 更多