admin管理员组

文章数量:1391836

I don't know if this is a dumb question, but how can I bine the ASP.NET authentication with OpenLayers?

I created a Login page to authenticate in OpenLayers (in C#, server side), this is my code

Uri uri = new Uri("http://"+username+":"+password+"@localhost:1979/geoserver/wms");
if (uri.Scheme == Uri.UriSchemeHttp)
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
    request.Method = WebRequestMethods.Http.Post;
           
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    StreamReader reader = new StreamReader(response.GetResponseStream()); string tmp = reader.ReadToEnd();
    response.Close();
    Response.Write(tmp);
}

I don't know if this is the right approach to resolve my problem, anyway if I reach my goal (authenticate with username and password in GeoServer), how can I bine this authentication with OpenLayers, which is in user side (JavaScript)

Thanks in advance.

I don't know if this is a dumb question, but how can I bine the ASP.NET authentication with OpenLayers?

I created a Login page to authenticate in OpenLayers (in C#, server side), this is my code

Uri uri = new Uri("http://"+username+":"+password+"@localhost:1979/geoserver/wms");
if (uri.Scheme == Uri.UriSchemeHttp)
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
    request.Method = WebRequestMethods.Http.Post;
           
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    StreamReader reader = new StreamReader(response.GetResponseStream()); string tmp = reader.ReadToEnd();
    response.Close();
    Response.Write(tmp);
}

I don't know if this is the right approach to resolve my problem, anyway if I reach my goal (authenticate with username and password in GeoServer), how can I bine this authentication with OpenLayers, which is in user side (JavaScript)

Thanks in advance.

Share Improve this question edited Oct 28, 2024 at 8:47 Mustafa Özçetin 3,0744 gold badges20 silver badges21 bronze badges asked Jun 8, 2012 at 14:25 Naty BizzNaty Bizz 2,3427 gold badges35 silver badges56 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

To authenticate with the GeoSerever from JavaScript side, you must to make a post to the GeoServer autentication servlet(j_spring_security_check). Try use this login function:

     function login (options) {
    // url del servlet del geoserver
    var url = options.server + "/geoserver/j_spring_security_check";
    // parametros para el login
    params = "username=" + options["user"] + "&password="
                + options["password"];

    var contentType = "application/x-www-form-urlencoded";
    //se inicializa la petición ajax
    var ajax = $.ajax({
        data : params,
        type : "POST",
        contentType : contentType,
        url : url
    });
    // se ejecuta cuando la peticion finaliza
    ajax.done(function() {

        if ($.cookie("JSESSIONID") != null && options && options.success) {
            options.success();
        }
    });
    // si ocurrio un error al realizar la peticion
    ajax.fail(function(data) {
        if (options && options.failure) {
            options.failure(data);
        }
    });
    // se ejecuta siempre al final de la petición, sin importar que esta
    // haya fallado
    ajax.always(function() {
        if (options && options.always) {
            options.always();
        }
    });
};

And use this way

 login({
    user:"admin" //geoserver user
    password: "adminPassword", 
    server : "http://192.168.10.1:8080", //geoserver host
    success : function(){
        alert("Login OK!");
    },
    failure : function(){
        alert("Login fail!");
    }
});

For some reason GeoServer doesn't properly handle the authentication passthrough after 2.7. So, I added a way to log in from a page method on the server and save the auth cookie in a session variable. Not pretty, but it works.

            'Post a login request to GS.
        Dim myCookies As String = ""
        Dim Method As String = "POST"

        Dim HttpWRequest As System.Net.HttpWebRequest = CType(WebRequest.Create("https://" & GSServer & "/geoserver/j_spring_security_check"), HttpWebRequest)

        Dim PostData As String = "username=" + UID + "&password=" + PWD
        HttpWRequest.KeepAlive = False
        HttpWRequest.Headers.Set("Pragma", "no-cache")
        'HttpWRequest.Headers.Set("Translate", "f")
        HttpWRequest.ContentType = "text/xml"
        HttpWRequest.ContentLength = PostData.Length

        'This is important, otherwise j_spring security check does an immediate redirect, and the cookie is lost.
        HttpWRequest.AllowAutoRedirect = False

        If String.IsNullOrEmpty(UID) = False Then
            HttpWRequest.Credentials = New NetworkCredential(UID, PWD)
        End If

        If String.IsNullOrEmpty(myCookies) = False Then
            HttpWRequest.Headers("Cookie") = myCookies
        End If

        'Set the request timeout to 5 minutes.
        HttpWRequest.Timeout = 300000
        ' set the request method
        HttpWRequest.Method = Method

        If Method = "POST" Or Method = "PUT" Then
            ' Store the data in a byte array.
            Dim ByteQuery() As Byte = System.Text.Encoding.ASCII.GetBytes(PostData)
            HttpWRequest.ContentLength = ByteQuery.Length
            Dim QueryStream As Stream = Nothing
            Try
                QueryStream = HttpWRequest.GetRequestStream()
            Catch e As Exception
                'WriteToLog(e.Message)
                Throw New ArgumentException("Couldn't log into GeoServer.")
            End Try
            ' Write the data to be posted to the Request stream.
            QueryStream.Write(ByteQuery, 0, ByteQuery.Length)
            QueryStream.Close()
        End If

        ' Send the request and get a response.

        Dim HttpWResponse As HttpWebResponse
        Try
            HttpWResponse = HttpWRequest.GetResponse()
        Catch e As Exception
            'WriteToLog(e.Message)
            Throw New ArgumentException("Couldn't log into GeoServer.")
        End Try

        ' Get the Response stream.
        Dim strm As Stream = HttpWResponse.GetResponseStream()

        ' Read the Response stream.
        Dim sr As StreamReader = New StreamReader(strm)
        Dim sText As String = sr.ReadToEnd()



        ' Close the stream.
        strm.Close()

        myCookies = HttpWResponse.GetResponseHeader("Set-Cookie")
        HttpContext.Current.Session("GeoServerSessionID") = myCookies
        ' Clean up.
        HttpWRequest = Nothing
        HttpWResponse = Nothing

        If sText.Contains("Invalid username/password bination") Or String.IsNullOrEmpty(myCookies) Then
            Throw New ArgumentException("Couldn't log into GeoServer.")
        End If

本文标签: javascriptAuthenticate in GeoServer with ASPNET and IISStack Overflow