1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.springframework.security.taglibs.authz;
17
18 import org.springframework.security.Authentication;
19
20 import org.springframework.security.context.SecurityContext;
21 import org.springframework.security.context.SecurityContextHolder;
22 import org.springframework.security.util.TextUtils;
23
24 import org.springframework.beans.BeanWrapperImpl;
25 import org.springframework.beans.BeansException;
26 import org.springframework.web.util.TagUtils;
27
28 import java.io.IOException;
29
30 import javax.servlet.jsp.JspException;
31 import javax.servlet.jsp.PageContext;
32 import javax.servlet.jsp.tagext.Tag;
33 import javax.servlet.jsp.tagext.TagSupport;
34
35
36
37
38
39
40
41
42
43
44 public class AuthenticationTag extends TagSupport {
45
46
47
48 private String var;
49 private String property;
50 private int scope;
51 private boolean scopeSpecified;
52
53
54
55
56 public AuthenticationTag() {
57 init();
58 }
59
60
61 private void init() {
62 var = null;
63 scopeSpecified = false;
64 scope = PageContext.PAGE_SCOPE;
65 }
66 public void setVar(String var) {
67 this.var = var;
68 }
69
70 public void setProperty(String operation) {
71 this.property = operation;
72 }
73
74 public void setScope(String scope) {
75 this.scope = TagUtils.getScope(scope);
76 this.scopeSpecified = true;
77 }
78
79 public int doStartTag() throws JspException {
80 return super.doStartTag();
81 }
82
83 public int doEndTag() throws JspException {
84 Object result = null;
85
86 if (property != null) {
87 if ((SecurityContextHolder.getContext() == null)
88 || !(SecurityContextHolder.getContext() instanceof SecurityContext)
89 || (SecurityContextHolder.getContext().getAuthentication() == null)) {
90 return Tag.EVAL_PAGE;
91 }
92
93 Authentication auth = SecurityContextHolder.getContext().getAuthentication();
94
95 if (auth.getPrincipal() == null) {
96 return Tag.EVAL_PAGE;
97 }
98
99 try {
100 BeanWrapperImpl wrapper = new BeanWrapperImpl(auth);
101 result = wrapper.getPropertyValue(property);
102 } catch (BeansException e) {
103 throw new JspException(e);
104 }
105 }
106
107 if (var != null) {
108
109
110
111
112
113
114 if (result != null) {
115 pageContext.setAttribute(var, result, scope);
116 } else {
117 if (scopeSpecified) {
118 pageContext.removeAttribute(var, scope);
119 } else {
120 pageContext.removeAttribute(var);
121 }
122 }
123 } else {
124 writeMessage(TextUtils.escapeEntities(String.valueOf(result)));
125 }
126 return EVAL_PAGE;
127 }
128
129 protected void writeMessage(String msg) throws JspException {
130 try {
131 pageContext.getOut().write(String.valueOf(msg));
132 } catch (IOException ioe) {
133 throw new JspException(ioe);
134 }
135 }
136 }