📄 authentication.java
字号:
package maca;
import java.io.*;
import java.net.*;
import java.util.*;
public class Authentication implements Serializable {
private static final int PRIVILEGE_ATTRIBUTE_CREDENTIALS = 10;
private Properties props = null;
private org.omg.CORBA.ORB orb = null;
private Security.AttributeType[] attrTypeList = null;
private SecurityLevel2.Credentials creds = null;
private DfResourceAccessDecision.AccessDecision ado = null;
private boolean firstLogin = true;
public Authentication(Properties properties) {
props = properties;
init();
}
private void init() {
InputStream in = null;
try {
if (props==null) {
System.out.println("Athentication: Reading default proporties file for MACA!");
in = maca.Authentication.class.getResourceAsStream("proporties/security.properties");
props.load(in);
in.close();
}
Properties orbProps = new Properties();
in = maca.Authentication.class.getResourceAsStream("proporties/orb.properties");
orbProps.load(in);
in.close();
orb = org.omg.CORBA.ORB.init(new String[0], orbProps);
Security.ExtensibleFamily extFamily = new Security.ExtensibleFamily((short) 0, (short) 1);
Security.AttributeType[] auxAttrType = {new Security.AttributeType(extFamily, Security.Role.value),
new Security.AttributeType(extFamily, Security.AccessId.value)};
attrTypeList = auxAttrType;
}
catch (java.io.IOException exc) {
System.out.println("Exception during initialization of authentication!");
System.out.println(exc);
}
}
public boolean access_allowed (String resource_name, String operation) {
if ((creds != null) && (ado != null)) {
Security.SecAttribute[] attrs = creds.get_attributes(attrTypeList);
DfResourceAccessDecision.ResourceNameComponent[] resNameCompts = {new DfResourceAccessDecision.ResourceNameComponent("Aplicacoes", resource_name)};
DfResourceAccessDecision.ResourceName resName = new DfResourceAccessDecision.ResourceName("ldap.incor.usp.br", resNameCompts);
try {
return ado.access_allowed(resName,
operation.equalsIgnoreCase("Execucao") ? "Execu玢o" : operation,
attrs);
}
catch (DfResourceAccessDecision.InternalError exc) {
System.out.println(exc);
}
}
return false;
}
public boolean authenticate(String userID, String password) {
try {
Security.ExtensibleFamily extFamily = new Security.ExtensibleFamily((short) 0, (short) 1);
Security.AttributeType attrType = new Security.AttributeType(extFamily, Security.Role.value);
Security.SecAttribute[] attrs = {new Security.SecAttribute(attrType, new byte [0], "".getBytes())};
SecurityLevel2.CredentialsHolder credHolder = new SecurityLevel2.CredentialsHolder();
Security.OpaqueHolder contData = new Security.OpaqueHolder();
Security.OpaqueHolder authEspec = new Security.OpaqueHolder();
//System.out.println("IORDefiningAuthorityURL: "+props.getProperty("IORDefiningAuthorityURL")+"/"+props.getProperty("PrincipalAuthenticatorName")+".ior");
URL iorURL = new URL(props.getProperty("IORDefiningAuthorityURL")+"/"+props.getProperty("PrincipalAuthenticatorName")+".ior");
BufferedReader iorStream = new BufferedReader(new InputStreamReader(iorURL.openStream()));
String paIOR = iorStream.readLine();
iorStream.close();
org.omg.CORBA.Object corbaObj = orb.string_to_object(paIOR);
SecurityLevel2.PrincipalAuthenticator pa = SecurityLevel2.PrincipalAuthenticatorHelper.narrow(corbaObj);
Security.AuthenticationStatus authStatus = pa.authenticate(0, userID, password.getBytes(), attrs, credHolder, contData, authEspec);
switch(authStatus.value()){
case Security.AuthenticationStatus._SecAuthContinue:
creds = credHolder.value;
String authMessage = new String(authEspec.value);
iorURL = new URL(props.getProperty("IORDefiningAuthorityURL")+"/"+props.getProperty("AccessDecisionObjectName")+".ior");
iorStream = new BufferedReader(new InputStreamReader(iorURL.openStream()));
String adoIOR = iorStream.readLine();
iorStream.close();
corbaObj = orb.string_to_object(adoIOR);
ado = DfResourceAccessDecision.AccessDecisionHelper.narrow(corbaObj);
firstLogin = userID.equalsIgnoreCase(new String(password));
password = null;
setActiveRole(getDefaultRole());
return true;
case Security.AuthenticationStatus._SecAuthSuccess:
authMessage = new String(authEspec.value);
creds = credHolder.value;
iorURL = new URL(props.getProperty("IORDefiningAuthorityURL")+"/"+props.getProperty("AccessDecisionObjectName")+".ior");
iorStream = new BufferedReader(new InputStreamReader(iorURL.openStream()));
adoIOR = iorStream.readLine();
iorStream.close();
corbaObj = orb.string_to_object(adoIOR);
ado = DfResourceAccessDecision.AccessDecisionHelper.narrow(corbaObj);
firstLogin = userID.equalsIgnoreCase(new String(password));
password = null;
setActiveRole(getDefaultRole());
return true;
case Security.AuthenticationStatus._SecAuthFailure:
return false;
case Security.AuthenticationStatus._SecAuthExpired:
authMessage = new String(authEspec.value);
return false;
}
password = null;
}
catch (java.net.MalformedURLException exc) {
System.out.println(exc.getMessage());
}
catch (java.io.IOException exc) {
System.out.println("Error in method: authenticate");
System.out.println(exc.getMessage());
}
return false;
}
public String[] getUserAttributes() {
return getUserAttributes(creds);
}
public synchronized void logout() {
if (creds != null) {
try {
creds.destroy();
}
catch (Exception ex) {
}
finally{
creds = null;
}
}
ado = null;
}
//---------------------------------------------------------------
private String getDefaultRole() {
try {
if (this.isValid()) {
Security.ExtensibleFamily extFamily = new Security.ExtensibleFamily((short) 0, (short) 1);
Security.AttributeType[] attrTypeRoleList = {new Security.AttributeType(extFamily, Security.Role.value)};
Security.SecAttribute[] attrs = creds.get_attributes(attrTypeRoleList);
for (int n = 1; n < attrs.length; n++) {
if ((attrs[n].attribute_type.attribute_family.family == 1) && // privilege attributes; family = 1
(attrs[n].attribute_type.attribute_type == Security.Role.value)) {
return new String(attrs[n].value);
}
}
}
}
catch (Exception exc) {
System.out.println(exc);
}
return "";
}
private boolean isValid() {
if(creds != null && ado != null){
try {
creds.refresh();
return true;
}
catch (Exception ex) {
ex.printStackTrace();
}
}
return false;
}
private boolean setActiveRole(String newRole) {
try {
if (this.isValid()) {
Security.ExtensibleFamily extFamily = new Security.ExtensibleFamily((short) 0, (short) 1);
Security.AttributeType attrType = new Security.AttributeType(extFamily, Security.Role.value);
Security.SecAttribute[] reqstedPriv = {new Security.SecAttribute(attrType, new byte [0], newRole.getBytes())};
Security.AttributeListHolder actualPriv = new Security.AttributeListHolder();
return creds.set_privileges(true, reqstedPriv, actualPriv);
}
else {
return false;
}
}
catch (Exception exc) {
System.out.println(exc.toString());
}
return false;
}
private String[] getUserAttributes (SecurityLevel2.Credentials creds) {
String[] atributos = {};
//Verifica se a credencial foi criada
if (creds != null) {
//Define a fam韑ia dos atributos de seguran鏰
Security.ExtensibleFamily extFamily = new Security.ExtensibleFamily((short) 0, (short) 1);
//Define o tipo de atributo a recuperar, o conjunto de atributos da conta do usu醨io, neste caso
Security.AttributeType[] attrType = {new Security.AttributeType(extFamily, Security.AttributeSet.value)};
//Recupera o valor do tipo de atributo a partir da credencial
//Cada elemento da lista retorna um atributo, do tipo string, com o seguinte formato:
//<nome do atributo>: <valor_1 do atributo>, <valor_2 do atributo>, ..., <valor_n do atributo>
Security.SecAttribute[] attrs = creds.get_attributes(attrType);
//Define a quantidade de atributos da conta retornados
atributos = new String[attrs.length];
//Examina a lista de valores em busca do tipo de atributo requisitado
for (int n = 0; n < attrs.length; n++) {
if ((attrs[n].attribute_type.attribute_family.family_definer == 0) &&
(attrs[n].attribute_type.attribute_family.family == 1) &&
(attrs[n].attribute_type.attribute_type == Security.AttributeSet.value)) {
atributos[n] = new String(attrs[n].value);
}
}
}
return atributos;
}
public String getUserInstitution(){
String[] list = getUserAttributes(creds);
for (int i = 0; i < list.length; i++) {
if(list[i].startsWith("ou")){
return list[i].substring(4);
}
}
return "";
}
/**
* SAMPLE USE OF THE CLASS
*/
/*
public static void main(String[] args) {
System.out.println("SAMPLE BEGIN.\n");
Authentication at = new Authentication(null);
boolean canAccess = at.authenticate("ramon", "ramones");//login, password
if(canAccess){
boolean canConfirmPatients = at.access_allowed("ConfirmacaoPacientes;Administracao;AcessoExterno","Execucao");
if(canConfirmPatients) System.out.println("You have the rights to confirm patients!");
else System.out.println("You DON'T have the right to confirm patients!");
}
at.logout();
System.out.println("\nSAMPLE ENDS.");
}*/
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -