JAAS 实现in Struts Web App使用XMLPolicy文件不改变VM安全

2016-02-19 13:09 7 1 收藏

生活已是百般艰难,为何不努力一点。下面图老师就给大家分享JAAS 实现in Struts Web App使用XMLPolicy文件不改变VM安全,希望可以让热爱学习的朋友们体会到设计的小小的乐趣。

【 tulaoshi.com - 编程语言 】

JAAS参考资料中流行的文章是扩展JAAS实现类实例级授权
  
  但它是基于JDK1.3,与目前的JDK1.4,JDK1.5不兼容,例如其中的配置如下:
  
  The following assumes you are using JDK 1.3 and the files were extracted to
  the d:JaasExample Directory. You will save some work by extracting the files
  to this directory otherwise you will have to modify the policy and the ResourceSecurity.XML
  policy files with the correct path names.
  
  1) Copy the jaas.jar and the jaasmod.jar to your JDK jrelibext directory
  (i.e. D:JDK1.3jrelibext).
  
  2) Add the following to the end of the Java.security file located in JDK's
  jrelibsecurity directory (i.e. D:JDK1.3jrelibsecurity):
  auth.policy.provider=com.ibm.resource.security.auth.XMLPolicyFile
  
  3) Execute the run.bat file.
  
  1.4以后为policy.provider=PolicyFile。而且需要修改java.security文件
  我经过2天的呕血奋战实现了不改变java VM环境和Web server环境,在struts下实现JAAS。
  步骤如下:
  
  1.      welcome.jsp, index.jsp, struts-config.xml
  
  
%@ taglib uri="/tags/struts-logic" prefix="logic" %
  logic:redirect forward="index"/
  %-- welcome.jsp
  Redirect default requests to Welcome global ActionForward.
  By using a redirect, the user-agent will change address to match the path of our Welcome ActionForward.
  --%

  
  index.jsp
  
  
%@ page contentType="text/Html; charset=UTF-8"%
  %@ taglib uri="/tags/struts-bean" prefix="bean"%
  %@ taglib uri="/tags/struts-html" prefix="html"%
  %@ taglib uri="/tags/struts-logic" prefix="logic"%
  
  html:html
  TitleLogon/Title
  body
  html:form action="/LoginAction.do"
          pUser ID: input type="text" name="userID" value="tyrone" /br
          Passord: input type="passWord" name="password" value="password"/br
          html:submit //p
  /html:form
  /body
  /html:html

  
  struts-config.xml
  
  
?xml version="1.0" encoding="ISO-8859-1" ?
  
  !DOCTYPE struts-config PUBLIC
            "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
            "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd"
  
  struts-config
  !-- ================================================ Form Bean Definitions --
  
      form-beans        
            !--2 Login formbean--    
          form-bean
              name="LoginForm"
              type="com.nova.colimas.web.form.LoginForm"/
      /form-beans
       global-forwards
          !-- Default forward to "Welcome" action --
          !-- Demonstrates using index.jsp to forward --
          forward
              name="index"
              path="/index.do"/
      /global-forwards
  !-- =========================================== Action Mapping Definitions --
      action-mappings
              !-- Default "Welcome" action --
              !-- Forwards to Welcome.jsp --
          action  path="/index"
                  type="com.nova.colimas.web.action.StartupServlet"
              forward name="sUCcess" path="/pages/index.jsp"/  
          /action
           !-- 2 Login --
            action    path="/LoginAction"
                type="com.nova.colimas.web.action.LoginAction"
                name="LoginForm"
                scope="request"
                input="/pages/indexcon.jsp"
                validate="true"
                  forward name="success" path="/pages/index.jsp"/
                  forward name="failure" path="/pages/index.jsp"/
           /action
      /action-mappings
  /struts-config

  
  2.      实现com.nova.colimas.web.action.StartupServlet用来初始化JAAS需要的系统属性
  
  
public class StartupServlet extends Action {
  
          public ActionForward execute(ActionMapping mapping,
                           ActionForm form,
                           HttpServletRequest request,
                           HttpServletResponse response)
          throws Exception{
                  // Initialization of the log
                  //LoggerFactory.setFactory(new EPricerLogFactory ());
                  //Log.info (this, "Startup of Settings application");
  
                  initJAAS();
                  return mapping.findForward("success");
          }
          //初始化JAAS需要的系统属性
          private void initJAAS(){
                  //set env variable
          //用于认证JAASConstants接口内保存login.config文件地址        System.setProperty("java.security.auth.login.config",JAASConstants.AUTH_SECURITY_LOGINFILE);
                  }
  }

  
  
public interface JAASConstants {
          String AUTH_SECURITY_POLICYXMLFILE="D:MyProjectcolimasclms-webcolimassecurity-policy.xml";
          String AUTH_SECURITY_LOGINFILE="D:MyProjectcolimasclms-webcolimaslogin.config";
          String AUTH_SECURITY_MODULENAME="ColimasLogin";
  }

  
  Login.config文件内容:
  
  
ColimasLogin {
     com.nova.colimas.security.auth.ColimasLoginModule required debug=true;
  };

  
  3.实现ColimasLoginModule登录模块
  
/*
   * Created on 2005/07/01
   *
   * TODO To change the template for this generated file go to
   * Window - Preferences - Java - Code Style - Code Templates
   */
  package com.nova.colimas.security.auth;
  
  import java.util.*;
  import javax.security.auth.*;
  import javax.security.auth.callback.*;
  import javax.security.auth.login.*;
  import javax.security.auth.spi.LoginModule;
  //import java.security.*;
  //import org.w3c.dom.traversal.*;
  import org.w3c.dom.*;
  //import org.apache.XPath.*;
  
  
  /**
   * @author tyrone
   *
   * TODO To change the template for this generated type comment go to
   * Window - Preferences - Java - Code Style - Code Templates
   */
  public class ColimasLoginModule implements LoginModule {
  
          private Subject subject;
          private CallbackHandler callbackHandler;
          private boolean debug = false;
          private boolean succeeded = false;
          private boolean commitSucceeded = false;
          private String username;
          private char[] password;
  
  
          /**
           * Initializes the codeLoginModule/code.
           *
           * @param subject the codeSubject/code to be authenticated.
           *
           * @param callbackHandler a codeCallbackHandler/code for
           * prompting and retrieving the userid and password from the user.
           *
           * @param sharedState shared codeLoginModule/code state.
           *
           * @param options options specified in the login configuration
           * file for this codeLoginModule/code.
           */
          public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
  
                  this.subject = subject;
                  this.callbackHandler = callbackHandler;
                  // initialize configuration options                
                  debug = "true".equalsIgnoreCase((String) options.get("debug"));
          }
  
  
          /**
           * Prompts the user for a userid and password.
           *
           * @return true if the authentication succeeded,
           * or false if this LoginModule should be ignored
           *
           * @exception FailedLoginException if the authentication fails.
           *
           * @exception LoginException if the codeLoginModule/code
           * is unable to authenticate.
           */
          public boolean login() throws LoginException {
  
                  if (callbackHandler == null)
                          throw new LoginException("Error: CallbackHandler cannot be null");
  
                  Callback[] callbacks = new Callback[2];
                  callbacks[0] = new NameCallback("userid: ");
                  callbacks[1] = new PasswordCallback("password: ", false);
  
                  try {
                          callbackHandler.handle(callbacks);
                          username = ((NameCallback) callbacks[0]).getName();
                          char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
                          
                          if (tmpPassword == null) {
                                  // treat a NULL password as an empty password
                                  tmpPassword = new char[0];
                          }
                          password = new char[tmpPassword.length];
                          System.arraycopy(tmpPassword, 0, password, 0, tmpPassword.length);
                          ((PasswordCallback) callbacks[1]).clearPassword();
  
                  } catch (java.io.IOException e) {
                          throw new LoginException(e.getMessage());
                  } catch (UnsupportedCallbackException e) {
                          throw new LoginException("Error: " + e.getMessage());
                  }
  
                  if(debug) {
                          //System.out.println("ColimasLoginModule: userid = " + username);
                          String pwd = new String(password);
                          System.out.println("ColimasLoginModule: password = " + pwd);
                  }
  
                  // Check the userid and password
                  if (isValidUser(username, password)) {
                          // authentication succeeded
                          if(debug)
                                  System.out.println("ColimasLoginModule: authentication succeeded");
                          succeeded = true;
                          return true;
                  } else {
                          // authentication failed
                          if(debug)
                                  System.out.println("ColimasLoginModule: authentication failed");
                          succeeded = false;
                          // clear the values
                          username = null;
                          password = null;
                          throw new FailedLoginException("Invalid userid or password");
                  }
                  
  
          }
  
  
          /**
           * This method is called if the LoginContext's overall authentication
           * succeeded (the relevant REQUIRED, REQUISITE, SUFFICIENT and
           * OPTIONAL LoginModules succeeded).
           * p
           * If this LoginModule's own authentication attempt succeeded
           * (checked by retrieving the private state saved by the
           * codelogin/code method), then this method associates the
           * relevant codePrincipAlexamples/code with the
           * codeSubject/code located in the codeLoginModule/code.
           * If this LoginModule's own authentication attempted failed, then
           * this method removes any state that was originally saved.
           *
           * @exception LoginException if the commit fails.
           *
           * @return true if this LoginModule's own login and commit attempts
           * succeeded, or false otherwise.
           */
          public boolean commit() throws LoginException {
  
                  if(succeeded == false)
                          return false;
  
                  subject.getPrincipals().add(new PrincipalUser(username));
                  subject.getPrincipals().addAll(getUserRoles(username));
                  
                  username = null;
                  password = null;
  
                  commitSucceeded = true;
                  return true;
          }
  
  
          /**
           * This method is called if the LoginContext's overall
           * authentication failed. (the relevant REQUIRED, REQUISITE,
           * SUFFICIENT and OPTIONAL LoginModules did not succeed).
           * p
           * If this LoginModule's own authentication attempt succeeded
           * (checked by retrieving the private state saved by the
           * codelogin/code and codecommit/code methods),
           * then this method cleans up any state that was originally
           * saved.
           *
           * @exception LoginException if the abort fails.
           *
           * @return false if this LoginModule's own login and/or commit attempts
           * failed, and true otherwise.
           */
          public boolean abort() throws LoginException {
  
                  if (succeeded == false)
                          return false;
                                                  
                  if(succeeded == true && commitSucceeded == false) {
                          // login succeeded but overall authentication failed
                          succeeded = false;
                          username = null;
                          password = null;
                  } else {
                          // overall authentication succeeded and commit
                          // succeeded, but someone else's commit failed.
                          Logout();
                  }
                  
                  return true;
          }
  
  
          /**
           * Logouts a Subject.
           * p
           * This method removes the codePrincipalExample/code
           * instances that were added by the codecommit/code
           * method.
           *
           * @exception LoginException if the Logout fails.
           *
           * @return true if this method succeeded, or false if this
           * LoginModule should be ignored.
           */
          public boolean Logout() throws LoginException {
  
                  subject.getPrincipals().clear();
                  succeeded = false;
                  succeeded = commitSucceeded;
                  username = null;
                  password = null;
                  
                  return true;
          }
  
          
          /**
           * Searches the users XML file for the specified
           * userid and password.
           */
          private boolean isValidUser(String uid, char[] passwd) {
                  try {
                          /*get userid and password from db */
                          String name="tyrone1979";
                          String password="197913";
                          if (uid.equals(name)){
                                  if (password.equals(new String(password)))
                                          return true;
                          }
  
                  } catch (Exception e) {
                          e.printStackTrace();
                          throw new RuntimeException(e.getMessage());
                  }
                  return false;
          }
  
  
          /**
           * Searches the user's group XML file and returns a
           * collection of PrincipalExamples for each group
           * a user is a member of.
           */
          private Collection getUserRoles(String username) {
                  Collection collection =null;
  
                  try {
                          /*
                                   get Roles from db
                                  */
                          ArrayList roles=new ArrayList();
                          roles.add(new PrincipalUser("00001"));
                          collection=roles;
                  } catch (Exception e) {
                          e.printStackTrace();
                          throw new RuntimeException(e.getMessage());
                  }
  
                  return collection;
          }
  
  }

  
  4. callback类
  
  
public class LoginCallbackHandler implements CallbackHandler {
          
          private String name=null;
          
          private String password=null;
          
          public LoginCallbackHandler(String name,String password){
                  super();
                  this.name=name;
                  this.password=password;
                  
          }
          /**
           * @see CallbackHandler#handle(Callback[])
           */
          public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                                          
                  for (int i = 0; i callbacks.length; i++) {
                          if (callbacks[i] instanceof TextOutputCallback) {
                                  TextOutputCallback textOutputCallback = (TextOutputCallback) callbacks[i];
                                  switch (textOutputCallback.getMessageType()) {
                                          case TextOutputCallback.INFORMATION :
                                                  //System.out.println(textOutputCallback.getMessage());
                                                  break;
                                          case TextOutputCallback.ERROR :
                                                  //System.out.println("ERROR: " + textOutputCallback.getMessage());
                                                  break;
                                          case TextOutputCallback.WARNING :
                                                  //System.out.println("WARNING: " + textOutputCallback.getMessage());
                                                  break;
                                          default :
                                                  throw new IOException("Invalid message type: " + textOutputCallback.getMessageType());
                                  }
                          } else if(callbacks[i] instanceof NameCallback) {
                                          // prompt the user for a userid
                                          NameCallback nc = (NameCallback) callbacks[i];
                                          nc.setName(this.name);
                          } else if(callbacks[i] instanceof PasswordCallback) {
                                          // prompt the user for the password
                                          PasswordCallback pc = (PasswordCallback) callbacks[i];
  
                                          pc.setPassword(this.password.toCharArray());
                          } else {
                                  throw new UnsupportedCallbackException(callbacks[i], "Invalid Callback");
                          }
                  }                                                
          }
  }

  
  5.com.nova.colimas.web.action.LoginAction类,实现认证
  
  
public class LoginAction extends Action {
          
          LoginContext loginContext=null;
          LoginForm loginForm=null;
          public ActionForward execute(ActionMapping mapping,
                           ActionForm form,
                           HttpServletRequest request,
                           HttpServletResponse response)
          throws Exception{
                  
                  /**
                   * 1 get Login form Bean
                   * 2 get the value
                   * 3 call JAAS Login Module
                   */
                  try {                
                          loginForm=(LoginForm)form;
                          loginContext=new LoginContext(JAASConstants.AUTH_SECURITY_MODULENAME, new LoginCallbackHandler(loginForm.getUserID(),loginForm.getPassword()));
                          
                  }catch(SecurityException e){
                          e.printStackTrace();
                  } catch (LoginException e) {
                          e.printStackTrace();
                          //System.exit(-1);
                  }
                  // Authenticate the user
                  try {
                          loginContext.login();//先运行ColimasLoginModule的initialize(Subject, CallbackHandler, Map, Map)方法,然后运行ColimasLoginModule的login()
                          System.out.println("Creating a new UserProfile...");                                        
                          System.out.println("Successfully!");        
                          
                  } catch (Exception e) {
                          System.out.println("Unexpected Exception - unable to continue");
                          e.printStackTrace();
                          //System.exit(-1);
                          return mapping.findForward("failure");
                  }                
        return mapping.findForward("success");
          }
  }

来源:http://www.tulaoshi.com/n/20160219/1603148.html

延伸阅读
PS如何不改变背景而能调亮皮肤   好多人问我怎么调可以把人的肤色提亮,而背景明暗不变呢? 嗯这篇示例就来讲讲三个简单好用的方法吧。当然,有需要的话,三个方法可以同时用在一张图上。 先看调整好的图片: 摄影师延延(微博:@摄影师延延)作品 调整完的图。 原图。 再看原图。好吧,这张照片明...
标签: excel
Excel2010不改变原数据顺序下怎么排序?   在Excel2010中,如果不改变原有数据的顺序下,怎样进行排序呢?下面图老师小编就为大家介绍Excel2010不改变原数据顺序下怎么排序的方法,一起来看看吧! 方法/步骤 1、编辑好的工作簿。 2、在E2的单元格中输入=RANK。 3、在输入(D2,$D$2:SD$21,0)后按住Enter键。 ...
Struts1.1比Struts1.0功能增强了很多。比如:提供DynaActionForms,可不用编写任何代码创建动态的ActionForm;多应用支持答应定义多个struts-config.XML配置文件等等。但JBuilder 9只直接支持Struts1.0,不直接支持Struts1.1,下面让我们来看看怎样让JBuilder 9支持Struts1.1。 首先下载 jakarta-struts-1.1,把整个目录放到jbuil...
这是action页面, package tester.business.maitain; import tclcc.tester.util.Selector; import org.apache.struts.action.*; import javax.servlet.http.*; import java.util.*; import org.apache.struts.upload.FormFile; import java.io.*; public class MaintainAction extends Action { public ActionForward execute(ActionM...
这是第二个类actionform, package tester.business.maitain; import org.apache.struts.action.*; import javax.servlet.http.*; import org.apache.struts.upload.*; public class MaintainForm extends ActionForm { /** private String p_title; private int post_index; private String issue_time; private String issue; priva...

经验教程

861

收藏

46
微博分享 QQ分享 QQ空间 手机页面 收藏网站 回到头部